How to use reduce Function In Javascript
In this approach, the reduce
function is used to accumulate objects into an array. For each element in the keys
array, an object is created with a key-value pair, and it is pushed into the accumulator array.
Example: This example uses reduce
Function
function createArrayOfObjectsUsingReduce(keys, values) {
return keys.reduce(function (acc, key, index) {
let obj = {};
obj[key] = values[index];
acc.push(obj);
return acc;
}, []);
}
// Example usage:
let keysArrayReduce = ['name', 'age', 'city'];
let valuesArrayReduce = ['John', 25, 'New York'];
let resultUsingReduce = createArrayOfObjectsUsingReduce(keysArrayReduce, valuesArrayReduce);
console.log(resultUsingReduce);
Output
[ { name: 'John' }, { age: 25 }, { city: 'New York' } ]
How to create an array of objects from multiple arrays in JavaScript ?
Creating an array of objects from multiple arrays in JavaScript involves combining corresponding elements from each array into single objects. This approach allows you to efficiently organize related data from separate arrays into a structured format, making it easier to manipulate and access the combined information.
Below are the approaches used to create an array of objects from multiple arrays in JavaScript:
Table of Content
- Using a Loop
- Using map Function
- Using reduce Function
- Using Object.fromEntries() method along with the map function
- Using Array.forEach()