Open In App

Convert 2D Array to Object using Map or Reduce in JavaScript

Last Updated : 25 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Converting a 2D array to an object is a common task in JavaScript development. This process involves transforming an array where each element represents a key-value pair into an object where keys are derived from one dimension of the array and values from another.

Problem Description:

Given a 2D array where each inner array contains a key-value pair, we aim to convert it into an object where the keys are extracted from the first element of each inner array and the values from the second element.

Example:

Consider the following 2D array:

const arr = [
["apple", 3],
["banana", 2],
["orange", 5]
];

Output:

{
"apple": 3,
"banana": 2,
"orange": 5
}

Using reduce() Method

In this approach we will first Initialize an empty object then Iterate over the 2D array using reduce() method and then extract the key and value from each inner array then assign the key-value pair to the accumulator object which will return the resulting object.

Example: Transforming a 2D array into an object using the reduce method for concise data conversion.

JavaScript
const arr = [
    ["apple", 3],
    ["banana", 2],
    ["orange", 5]
];

const objReduce = arr
    .reduce((acc, [key, value]) => {
        acc[key] = value;
        return acc;
    }, {});
console.log(objReduce);

Output
{ apple: 3, banana: 2, orange: 5 }

Time Complexity: O(n), where n is the number of elements in the 2D array.

Space Complexity: O(n)

Using map() Method and Object.fromEntries()

In this approach we use the map method to map each inner array to a new array where the key and value are swapped. It Uses the Object.fromEntries() to convert the mapped array into an object.

Example: Converting a 2D array into an object map for efficient data representation.

JavaScript
const arr = [
    ["apple", 3],
    ["banana", 2],
    ["orange", 5]
];

const objMap = Object
    .fromEntries(arr.map(([key, value]) => [key, value]));
console.log(objMap);

Output
{ apple: 3, banana: 2, orange: 5 }

Time Complexity: O(n), where n is the number of elements in the 2D array.

Space Complexity: O(n)


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads