DEV Community

vishwa v
vishwa v

Posted on • Edited on

Js(methods-3)

JavaScript Array flatMap()
The flatMap() method first maps all elements of an array and then creates a new array by flattening the array.

const myArr = [1, 2, 3, 4, 5, 6];
const newArr = myArr.flatMap(x => [x, x * 10]);

Enter fullscreen mode Exit fullscreen mode

JavaScript Array filter()
The filter() method creates a new array with array elements that pass a test.

This example creates a new array from elements with a value larger than 18:

const numbers = [45, 4, 9, 16, 25];
const over18 = numbers.filter(myFunction);

function myFunction(value, index, array) {
  return value > 18;
}
Enter fullscreen mode Exit fullscreen mode

JavaScript Array reduce()
The reduce() method runs a function on each array element to produce a single value.

The reduce() method works from left-to-right in the array. See also reduceRight().

const numbers = [45, 4, 9, 16, 25];
let sum = numbers.reduce(myFunction);

function myFunction(total, value, index, array) {
  return total + value;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)