High-Order Array Methods
High-order array methods in JavaScript, including map(), filter(), and reduce(), provide powerful tools to efficiently manipulate and process arrays, enhancing code readability and simplicity.
Map() method
It applies a given function on all the elements of the array and returns the updated array. It is the simpler and shorter code instead of a loop. The map is similar to the following code:
Syntax
array.map(callback(element, index, array))Let's understand this with the help of example:
function triple(n){
return n*3;
}
arr = new Array(1, 2, 3, 6, 5, 4);
var new_arr = arr.map(triple)
console.log(new_arr);
Output:
[ 3, 6, 9, 18, 15, 12 ]
Reduce() method
It reduces all the elements of the array to a single value by repeatedly applying a function. It is an alternative of using a loop and updating the result for every scanned element. Reduce can be used in place of the following code:
Syntax
array.reduce(callback(accumulator, element, index, array), initialValue)Let's understand this with the help of example
function product(a, b){
return a * b;
}
arr = new Array(1, 2, 3, 6, 5, 4);
var product_of_arr = arr.reduce(product)
console.log(product_of_arr)
Output:
720Filter() method
Filter method filters the elements of the array that return false for the applied condition and returns the array which contains elements that satisfy the applied condition.
Syntax:
array.filter(callback(element, index, array))Let's understand this with the help of example
arr = new Array(1, 2, 3, 6, 5, 4);
var new_arr = arr.filter(function (x){
return x % 2==0;
});
console.log(new_arr)
Output:
[ 2, 6, 4 ]