How to use reduce() In Javascript
Reduce() method is used to iterate through an array of objects. It accumulate values under duplicate keys into a new object. If a key already exists, append the value; otherwise, create a new key-value pair.
Syntax:
array.reduce( function(total, currentValue, currentIndex, arr),
initialValue )
Example: In this example we are using reduce() method to iterate through an array of objects (myArray). It accumulates values under duplicate keys, creating a new object (resultObj).
const myArray = [
{ key: "id", value: 1 },
{ key: "name", value: "Bhavna" },
{ key: "id", value: 2 },
{ key: "name", value: "Sharma" },
];
const resultObj = myArray.reduce((acc, obj) => {
acc[obj.key] ? acc[obj.key].push(obj.value) : (acc[obj.key] = [obj.value]);
return acc;
}, {});
console.log(resultObj);
Output
{ id: [ 1, 2 ], name: [ 'Bhavna', 'Sharma' ] }
How to Add Duplicate Object Key with Different Value to Another Object in an Array in JavaScript ?
Adding duplicate object keys with different values to another object in an array in JavaScript refers to aggregating values under the same key from multiple objects in an array, creating a new object where each key corresponds to an array of associated values.
Table of Content
- Using for…of Loop
- Using reduce()
- Using a Map for Multiple Values
- Using forEach()