Would you like to clone this notebook?

When you clone a notebook you are able to make changes without affecting the original notebook.

Cancel

array.reduce()

node v8.17.0
version: 4.0.0
endpointsharetweet
QUESTION 1 - SUM VALUES OF ARRAY
const integer = [12, 23, 34, 45, 56]
Below is the traditional way to sum values in an array to a single value.
// Traditional way // let sumAll = 0; // for(let i = 0; i < integer.length; i++){ // sumAll += integer[i]; // } // sumAll;
Now try to use .reduce() to produce same result.
// Use .reduce() function here. // Output: 170
QUESTION 2 - FLATTEN ARRAY Given below is an array of array.
const array1 = [[0, 1], [2, 3], [4, 5]];
Now, use .reduce() to flatten the array into single array
// Hint: Use .concat // Output: [0, 1, 2, 3, 4, 5]
QUESTION 3 - COUNTING INSTANCES OF VALUES IN AN OBJECT Given below array of names.
const names = ['Hafiz', 'Fatin', 'Naim', 'Amirah', 'Afiq', 'Hafiz', 'Afiq', 'Afiq'];
Now use .reduce() to count the instances values.
// Answer here // Output: {Afiq: 3, Amirah: 1, Fatin: 1, Hafiz: 2, Naim: 1}
QUESTION 4 - BONDING ARRAY
Given below an array of JSON object.
const friends = [ { name: 'Nasir', books: ['Blank', 'Harry Potter'], age: 12 }, { name: 'Shahrul', books: ['War and peace', 'Romeo and Juliet'], age: 45 }, { name: 'Arif', books: ['The Lord of the Rings', 'The Shining'], age: 20 } ];
Use reduce() method to find/list all books within the array.
// Answer here // Output: ['Blank','Harry Potter','War and peace','Romeo and Juliet','The Lord of the Rings','The Shining' ]
Loading…

no comments

    sign in to comment