Built-in JavaScript functions for array
There are some common operations which developers need to perform frequently on arrays. Searching an element, finding position of an element in the array, filtering, iterating over the array accumulating some values in variables…all these are examples of common work for which developer has to write code. To save programmer’s time, JS provide some built in functions for arrays.
Functions which we will look here are as following:
1. map
2. filter
3. reduce
4. find
5. findIndex
First, we declare an array:
var numbers = [10,12,15,67,5];
- Map function: this function returns a new array containing elements which are the result of some operation performed on each element of original array.
var mapNumbers = numbers.map(number=>{
return number *3;
});
console.log(mapNumbers); //output: [30,36,45,201,15]
2. Filter function: this function returns a new array containing elements from original array which satisfies mentioned condition within the callback function.
var filteredNums = numbers.filter(number=>{
return number>30;
});
console.log(mapNumbers); //output: [67]
3. Reduce function: this function returns a single value obtained as a result of some operation which leads to accumulation of value. For example, addition of all elements in the array.
var accumulator = numbers.reduce(
function(accumulator,number){
return accumulator + number;
}
);
console.log(accumulator); //output: 109
The callback function in reduce function accepts two arguments: one is the accumulator in which value is being accumulated or added up, second is the element is one of the operand used in addition and is also an element of array numbers.
4. Find function: this returns an element of the array which satisfies the condition mentioned in callback function and returns true. If none satisfies, then it returns undefined.
var search = numbers.find(num=> {return num==15});
console.log(search); //output: 15
5. FindIndex function: returns first position of the element in array which satisfies a given condition else returns -1.
var position = numbers.findIndex(number=>{ return number == 12;})
The example here returns 1 as the condition: number ==12 return true when value of number becomes 12.