Reducer Method and Some useful examples
A Reducer() method works on each array element. The final result of running the reducer across all elements of the array is a single value. The array element at index 0 is used as the initial value and iteration starts from the next element. we can assign initial value which is required as needed.
The?reduce()?method takes two arguments: a callback function and an optional initial value. If an initial value is provided,?reduce()?calls the "reducer" callback function on each element in the array, in order. If no initial value is provided,?reduce()?calls the callback function on each element in the array after the first element.
reduce()?returns the value that is returned from the callback function on the final iteration of the array.
Some useful example of reduce method
following solution with flat() method.
const arr = [1,[2,[3,[4,[5]]]]];
const flatArray = arr.flat(Infinity);
following solution with Reduce method
const flat = array => {
return array.reduce((acc, it) => acc.concat(Array.isArray(it) ? flat(it) : it),[])
}
const arr = [1,[2,[3,[4,[5]]]]];
const flatArray = flat(arr)
2. Unique Array without using set() method
const arr = [1,2,3,4,-1,0
const uniqueArray = arr.reduce((acc,it) => acc.includes(it) ? acc : [...acc, it], [])]
3. Count the number of array members
const count = arr => arr.reduce((acc,it) => (acc.set(it,(acc.get(it) || 0) + 1), acc),new Map())
const arr = [1,2,1,3,2,-1,0,1]
for above code snippet we will get Map output with entries like key and value pair. here keys are unique array element and values are actual count of that key in array.