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

Javascript
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()

Similar Reads

Using a Loop

This approach uses a for loop to iterate through the keys and values arrays, creating an object for each pair and pushing it into an array. The resulting array contains objects with keys from the keys array and corresponding values from the values array....

Using map Function

The map function is employed to create an array of objects. For each element in the keys array, an object is created with a key-value pair, where the key is from the keys array, and the value is from the corresponding position in the values array....

Using reduce Function

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

Using Object.fromEntries() method along with the map function

This method utilizes Object.fromEntries() along with the map function to create an array of objects. It first zips the keys and values arrays into an array of key-value pairs and then uses Object.fromEntries() to convert each pair into an object....

Using Array.forEach()

To create an array of objects from multiple arrays in JavaScript using Array.forEach(), iterate over the keys array. For each key, push an object into the result array with the corresponding value from the values array....