How to use Array reduce() method on JSON object

← PrevNext →

I have explained the reduce() method in my previous post. The method takes an array of elements and reduces it down to a single value. But, do you know, it also works on JSON object, of any type? I’ll explain this with two simple examples.

1st Example

In this example, I have a JSON array, with few objects in it. I want to calculate the sum of all the marks obtained a student in various subjects.

<script>
  let total_marks = () => {
    const student = '[{"subject":"science", "marks": 87}, ' +
          '{"subject":"math", "marks": 82}, ' +
          '{"subject":"sanskrit", "marks": 91}]';
    
    const arr = JSON.parse(student);

    const arrMarks = arr.map(students => students.marks); // get all the marks.
    const result = arrMarks.reduce(sum, 0);		// now calculate the sum.
    document.write ('total marks: ' + result);
  }

  // return the sum.
  let sum = (prev, cur) => {
    return prev + cur;
  }

  total_marks();
</script>
Try it
Here, I am using two methods. The map() method followed by the reduce() method.

The map() extracts all marks from the JSON and stores the data it in an array.

The reduce() runs a callback function named sum() and returns the total marks obtained.

👉   You can write the above code using Arrow function.

<script>
  let total_marks = () => {
    const student = '[{"subject":"science", "marks": 87}, ' +
          '{"subject":"math", "marks": 82}, ' +
          '{"subject":"sanskrit", "marks": 91}]';
    
    const arr = JSON.parse(student);

    // get all the marks.
    const arrMarks = arr.map(students => students.marks);
    const result = arrMarks.reduce((prev, cur) => prev + cur);    // using arrow function (short and sweet).
    
    document.write ('total marks obtained: ' + result);
  }

  total_marks();
</script>

Ok, don't want to use the map() method? No problem. You can run a similar code using only the reduce() method on a JSON object. See the 2nd example.

2nd Example

Here I have a JSON object with two values, name and type (of birds). I’ll use reduce() method to get a particular type of birds from the JSON object.

<body>
  <div id='result'></div>       <!--   show result here. -->
</body>

<script>
  let b = '';
  let get_bird_type = () => {
    const data = {"birds": [
        { "name": "Bald Eagle", "type": "Hawk" },
        { "name": "Rock Pigeon", "type": "Dove" },
        { "name": "Black Vulture", "type": "Hawk" }
      ]};

    const result = data.birds.reduce(btype, 0);
    
    let cont = document.getElementById('result');
    cont.innerHTML = result;   // output: Bald Eagle, Black Vulture
  }

  // callback function
  let btype = (prev, bird) => {
    if (bird.type === 'Hawk') {	    // check type of bird. Change bird type and check.
      b = b + bird.name + '<br />';
    }
    return b;	// return bird name.
  }

  get_bird_type();
</script>
Try it

When the callback function is invoked, it checks the bird type using a condition and accordingly returns the result as a single value.

So, if the condition is Hawk, it stores the name of all the birds of type Hawk in a variable and returns.

👉   Alternatively, you can write the above code using Arrow function.

<script>
  let b = '';
  let get_bird_type = () => {
    const data = {"birds": [
        { "name": "Bald Eagle", "type": "Hawk" },
        { "name": "Rock Pigeon", "type": "Dove" },
        { "name": "Black Vulture", "type": "Hawk" }
      ]};

    // using Arrow function.
    const result = 
        data.birds.reduce((prev, cur) =>
        cur.type === 'Dove' ? b = b + cur.name + '<br />' : b, '');  // output: Rock Pigeon
    
    let cont = document.getElementById('result');
    cont.innerHTML = result;
  }

  get_bird_type();
</script>
The Arrow function has an advantage. Just a one-line code performs the whole task.

Also, see how I am using the “ternary operator” with the Arrow function, to reduce the array into a single value.

Thanks for reading.

Articles you don't want to miss.

What is map() function in JavaScript? Benefits of using map() function in your application.
How to get the x Character (any particular character) in a String using charAt() method in JavaScript
How to create a simple CRUD application using only JavaScript

← PreviousNext →