Go through arrays in JavaScript (Part III)
Lets talk about array and some more array methods
Hey guys , welcome to Omkar's blogs .
Today we talk about some more array methods. Here are some array methods -
- reduce()
- filter()
reduce()
The reducer() method execute a reducer function on each element of an array to return single output value.
const numList = [1, 2, 3, 4, 5, 6, 7, 8, 9];
// function to add each elements
function addList(accumulator, currentValue) {
return accumulator + currentValue;
}
// reduce add each element of the array
let addNumList = numList.reduce(addList);
console.log(addNumList);
// Output: 45
reducer() syntax
arr.reduce(callback(accumulator, currentValue), initialValue)
In reducer() method , we can pass two parameters -
- First parameter is
callback
function which execute on each array elements . In callback function,accumulator
stores callback return values and current element passed from array store incurrentValue
. - Second parameter is
initialValue
, which is optional parameter. This value will be pass to callback on first time when callback is call. The first element acts as the accumulator on the first call and callback() won't execute on it.
reduce() does not change the original array.
filter()
The filter() method return the new array with values that satisfies the conditions given by function.
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
// function to check even numbers
function checkEven(number) {
if (number % 2 == 0)
return true;
else
return false;
}
// create a new array by filter even numbers from the array
let evenNumbers = numbers.filter(checkEven);
console.log(evenNumbers);
// Output: [ 2, 4, 6, 8]
filter() syntax
arr.filter(callback(element), thisArg)
In filter() method , we can pass two parameters -
- First parameter is a callback function which executes on each array elements and return boolean values (true , false).
- Second parameter is optional parameter
thisArg
. By default this value is undefined. This value is use asthis
when executingcallback
.
filter() method return new array with values which satisfies conditions given by function.