Tutorial Playlist

JavaScript Tutorial: Learn JavaScript from Scratch

Overview

An Introduction to JavaScript: Here Is All You Need to Know

Lesson - 1

JavaScript Hello World: Here's What You Need To Know

Lesson - 2

All You Need to Know About JavaScript Arrays

Lesson - 3

Using Array Filter In JavaScript to Filter Array Elements

Lesson - 4

Everything You Need to Know About Array Reduce JavaScript

Lesson - 5

Introduction To JavaScript Loops: Do-While, For, For-In Loops

Lesson - 6

All You Need to Learn About Javascript Functions

Lesson - 7

The Best Guide on How to Implement JavaScript Closures

Lesson - 8

JavaScript “This” Keyword and How to Implement It

Lesson - 9

How to Implement JavaScript Form Validation

Lesson - 10

An Introduction Guide To JavaScript RegEx

Lesson - 11

How to Validate an Email Address in JavaScript?

Lesson - 12

All You Need to Know About JavaScript Promises

Lesson - 13

How to Implement JavaScript Async/Await

Lesson - 14

JavaScript DOM Tutorial: 2020 Edition

Lesson - 15

JavaScript Objects: Properties, Methods, and Accessors

Lesson - 16

An Introduction to Javascript Games: The Best Guide

Lesson - 17

An Easy Guide To Build A Calculator App In JavaScript

Lesson - 18

Javascript Projects: The Best Guide

Lesson - 19

What is OOP in JavaScript? How is it Implemented?

Lesson - 20

The Best Guide to Understanding JavaScript Learning Path

Lesson - 21

Java Vs .NET: Which Is the Best Technology to Choose?

Lesson - 22

Top 40 JavaScript Interview Questions You Should Know

Lesson - 23

Typeof in JavaScript: Checking Data Types Using the Typeof Operator

Lesson - 24

Tips and Tricks That You Should Know Before Going to a Coding Interview

Lesson - 25

Callback Functions in JavaScript

Lesson - 26
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.

Post Graduate Program: Full Stack Web Development

in Collaboration with Caltech CTMEEnroll Now
Post Graduate Program: Full Stack Web Development

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.

Free Course: JavaScript for Beginners

Learn the Basics of JavaScriptEnroll Now
Free Course: JavaScript for Beginners

Array Reduce JavaScript 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

Full Stack Web Developer Course

To become an expert in MEAN StackView Course
Full Stack Web Developer Course

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.

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
Master the complete JavaScript fundamentals, jQuery, Ajax, and more with the Javascript Certification Training Course. Check out the course preview!

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 also sign up on our SkillUp platform. It is a Simplilearn initiative that offers free online courses to help you hone your skills in multiple programming languages, including JavaScript. Besides, you can also apply for our Full-Stack Web Development Certification Course 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.

About the Author

SimplilearnSimplilearn

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

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