Array.Filter and Array.Reduce are pertinent functions in Javascript. They give lot of flexibility to the developer.
1. Array.filter
This function helps to generate another resultant array after an expression is applied to each element of an Array. Let's take an example:
10
[ 10, 20, 30, 40, 50, 60 ]
Happy Coding! | dhandrohit@gmail.com
1. Array.filter
This function helps to generate another resultant array after an expression is applied to each element of an Array. Let's take an example:
let cities = ["Toronto","Vancouver","London","New York", "Las Vegas"];
var result = cities.filter((city)=>{
return (city.length > 8);
});
console.log(result);
The above code will filter cities based on the length of name of the cities. All the city names that have length greater than 8 characters will be stored in a new array.The output will be:
[ 'Vancouver', 'Las Vegas' ]
2. Array.Reduce
This function executes the callback function once for each element in the array. It works with two main parameters i.e. accumulator, currentValue
let numbers = [1,2,3,4];
var total = numbers.reduce((sum, no)=> {
return (sum + no);
});
console.log(total);
The above example will get the total of all the element so the array. So the result will be:10
let sum = [{a:1}, {a:2}, {a:3}].reduce(function(accumumator, currentValue){
return (accumumator + currentValue.a);
},0);
console.log(sum);
The above code will calculate the total of the all elements based on objects. Also we are giving "0" as the initial value that will be used in the callbacks. let joinedElements = [[10,20], [30,40],[50,60]].reduce((accumumator,currentValue)=>{
return accumumator.concat(currentValue);
});
console.log(joinedElements);
The above code will join all elements of an array of arrays into a single array. The output will be:[ 10, 20, 30, 40, 50, 60 ]
Happy Coding! | dhandrohit@gmail.com
Comments