Everything You Need to Know About Array Reduce JavaScript

The array reduce in JavaScript is a predefined method used to reduce an array to a single value by passing a callback function on each element of the array. It accepts a function executed on all the items of the specified array in the left-to-right sequence. The returned single value is stored in the accumulator. Thus, array reduce JavaScript is a non-mutating method. This means that instead of changing the actual value variable, it will hold the computed value in the accumulator without changing the original value variable.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Array Reduce in JavaScript Syntax and Parameter Values

The array reduce JavaScript syntax is:

array.reduce(callbackfn(total, curValue, curIndex, array), initialValue)

In the above syntax:

  • Callbackfn: This is a required parameter that holds the function that is supposed to be executed on every array element. The callbackfn parameter further accepts four parameters that are:
    • Total: It is a required parameter, also called accumulator, that holds the initialValue in the beginning and then the last returned value of the function.
    • curValue: This is a required argument that holds the value of the current element being executed.
    • curIndex: It is an optional parameter holding the index of the current value.
    • Array: This is also an optional parameter that holds the complete array object on which the operation is performed.
  • initialValue: This is an optional parameter and holds the initial value passed to the function.

What Are Reducer and Accumulator?

Reducer and accumulator are both essential terminologies used while working with array reduce in JavaScript.

  • Reducer: Reducer is the action performed on the array that reduces the entire array to a single value.
  • Accumulator: The accumulator is the single value we get at the end of the execution after the reducer’s job is completed.

Properties of Array Reduce in JavaScript

The array reduce method has the following properties:

  • If you provide the initialValue, the accumulator will be equal to that value, and the curValue will be similar to the first value of the array.
  • If you don’t provide the initialValue, the accumulator will be equal to the first element of the array, and the curValue will be similar to the second element’s value.
  • If you use array reduce on an array without any elements and don’t provide initialValue, it will throw a TypeError.
  • If the array is empty and initialValue is provided, or the array has only one element and initialValue, the reduce method will return the same value without calling the callbackfn.

Learn From The Best Mentors in the Industry!

Automation Testing Masters ProgramExplore Program
Learn From The Best Mentors in the Industry!

JavaScript Array Reduce Examples

Now that we know about the array reduce in JavaScript and its syntax, let’s look at some examples to understand the concept better.

Example 1: Summing All the Values

In this example, we will implement array reduce in JavaScript to sum the array elements and log the result to the console.

let num = [5, 9, 12, 24, 67]

let sum = num.reduce(function (accumulator, curValue) {

  return accumulator + curValue

}, 0)

console.log(sum)

Output:

Array_Reduce_JavaScript_1

You can also write the same code with arrow functions. Here’s the code for the same:

let num = [5, 9, 12, 24, 67]

let sum = num.reduce((accumulator, curValue) => accumulator + curValue, 0)

console.log(sum)

Output:

Array_Reduce_JavaScript_1

Example 2: Summing Values in an Object Array Using Array Reduce JavaScript

To sum values from an object array, we need to pass initialValue to the method. This would force all the elements of the array to pass through the function and give the desired result.

let initialValue = 0

let obj = [{n: 5}, {n: 9}, {n: 13}, {n: 25}, {n: 40}]

let sum = obj.reduce(function (accumulator, curValue) {

    return accumulator + curValue.n

}, initialValue)

console.log(sum)

Output:

Array_Reduce_JavaScript_2

Example 3: Flattening an Array of Arrays With Reduce Method

This time we will take an array of arrays and reduce (flatten) it to a single array. The code below demonstrates the same.

let mulArray = [[3, 5], [1, 7], [12, 9]]

let newArray = mulArray.reduce(function(accumulator, curValue) {

    return accumulator.concat(curValue)

  },[]

)

console.log(newArray)

Output:

Array_Reduce_JavaScript_3

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Example 4: Counting Instances in an Object Using Array Reduce in JavaScript

Here, we will create an array with car names and use the array reduce in JavaScript to count the number of instances when a car name has occurred.

let myCars = ['Mercedes-Benz', 'Jeep', 'Ferrari', 'Lamborghini', 'Mercedes-Benz', 'BMW', 'Ferrari']

let instances = myCars.reduce(function (allCars, car) {

  if (car in allCars) {

    allCars[car]++

  }

  else {

    allCars[car] = 1

  }

  return allCars

}, {})

console.log(instances)

Output:

Array_Reduce_JavaScript_4

Example 5: Grouping Objects With Array Reduce in JavaScript

This example groups objects based on a property value using the JavaScript array reduce method.

let student = [

  { name: 'David', age: 23, hobby: 'fishing' },

  { name: 'Rachel', age: 25, hobby: 'cooking' },

  { name: 'Rahul', age: 22, hobby: 'fishing' }

];

function myFunc(obj, prop) {

  return obj.reduce(function (acc, item) {

    let key = item[prop]

    if (!acc[key]) {

      acc[key] = []

    }

    acc[key].push(item)

    return acc

  }, {})

}

let groupedStudent = myFunc(student, 'hobby')

console.log(groupedStudent)

Output:

Array_Reduce_JavaScript_5.

Prepare Yourself to Answer All Questions!

Automation Testing Masters ProgramExplore Program
Prepare Yourself to Answer All Questions!

Example 6: Removing Duplicates With Array Reduce

For this example, we will create an array with multiple recurring values and then use the array reduce in JavaScript to eliminate those repeating values.

let array = [2, 5, 7, 5, 12, 9, 7, 5, 4, 3, 5, 2, 4, 15]

let newArray = array.reduce(function (accumulator, curValue) {

  if (accumulator.indexOf(curValue) === -1) {

    accumulator.push(curValue)

  }

  return accumulator

}, [])

console.log(newArray)

Output:

Array_Reduce_JavaScript_6

Browsers Supporting Array Reduce in JavaScript

The following list of browsers support the use of array reduce in JavaScript:

  • Google Chrome
  • Microsoft Edge 9.0
  • Mozilla Firefox 3.0
  • Safari 5.0
  • Opera 10.5

Conclusion

In this article, you have learned everything about array reduce in JavaScript and how you can use this method to reduce an array to a single value. If you want to learn more such JavaScript fundamentals, you can opt for Simplilearn’s JavaScript Certification Course. The course helps you understand various programming language concepts while providing applied learning on building a chat application.

You can apply for our Full Stack Java Developer to master other programming languages along with JavaScript. Learning multiple development languages is essential in today’s competitive world, and our course helps you with just that. It lets you get acquainted with the fundamentals of the most popular development languages and the relevant tools. You also get a certification upon completing the course to add credibility to your skills and help you land a high-paying software development job.

If you have any questions of queries, feel free to post them in the comments below. Our team will get back to you at the earliest.

About the Author

Ravikiran A SRavikiran A S

Ravikiran A S works with Simplilearn as a Research Analyst. He an enthusiastic geek always in the hunt to learn the latest technologies. He is proficient with Java Programming Language, Big Data, and powerful Big Data Frameworks like Apache Hadoop and Apache Spark.

View More
  • Acknowledgement
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, OPM3 and the PMI ATP seal are the registered marks of the Project Management Institute, Inc.