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

  1. Flatten a multi-level nested array

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.

To view or add a comment, sign in

More articles by Shubham Hirap

  • Bundler in React.js

    Today I was trying to read and watch some videos about the bundler specifically about the "parcel" and suddenly I one…

  • React Hook: useCallback()

    useCallback() is a React Hook that lets you cache a function definition between re-renders. const cachedFn =…

  • React Hook: useMemo()

    useMemo() Hook "useMemo" is a React Hook that lets you cache the result of a calculation between re-renders…

  • Atomic Design Pattern

    Introduction As a React JS Developer, I work on UI components on daily basis. Component reusability is the main…

    1 Comment
  • BEM Methodology in short

    Introduction I am working as a React frontend developer so yesterday I got introduced to a new concept BEM Methodology.…

  • Javascript Arrow function

    An arrow function expression is a compact alternative to a traditional function expression, but is limited and can't be…

    2 Comments

Insights from the community

Others also viewed

Explore topics