Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

JavaScript Array map()

The map() method generates a new array by applying a function to each element within the original array.

It does not execute the function for array elements lacking values, and it does not alter the original array.

In the following example, each value within the array is multiplied by 2:

Example

const numbers1 = [45491625];
const numbers2 = numbers1.map(myFunction);

function myFunction(value, index, array) {
  return value * 2;
}

Keep in mind that the callback function accepts three arguments:

  • The item value
  • The item index
  • The array itself

When a callback function utilizes only the value parameter, you can omit the index and array parameters.

Example

const numbers1 = [45491625];
const numbers2 = numbers1.map(myFunction);

function myFunction(value) {
  return value * 2;
}

JavaScript Array flatMap()

Introduced in ES2019, the Array flatMap() method in JavaScript initially maps all elements of an array and subsequently generates a new array by flattening it.

Example

const myArr = [123456];
const newArr = myArr.flatMap((x) => x * 2);

Browser Support

JavaScript Array flatMap() is compatible with all modern browsers, with support extending back to January 2020.

IMG_4150

JavaScript Array filter()

The filter() method generates a new array comprising elements from the original array that satisfy a given test.

In this example, a new array is created containing elements with values greater than 18:

Example

const numbers = [45491625];
const over18 = numbers.filter(myFunction);

function myFunction(value, index, array) {
  return value > 18;
}

It’s important to note that the callback function accepts three arguments:

  • The item value
  • The item index
  • The array itself

In the provided example, since the callback function doesn’t utilize the index and array parameters, they can be excluded:

Example

const numbers = [45491625];
const over18 = numbers.filter(myFunction);

function myFunction(value) {
  return value > 18;
}