Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an associative array in JavaScript using the map function

I've an array of objects with the following format

[{'list': 'one', 'item': 1},
 {'list': 'one', 'item': 2},
 {'list': 'one', 'item': 3},
 {'list': 'two', 'item': 1},
 {'list': 'two', 'item': 2}]

And I want to transform it like this

[{'one': [1, 2, 3]},
 {'two': [1, 2]}]

How can I do it using the Array.map function? Is it the best alternative?

like image 781
Ezequiel Miranda Avatar asked Sep 16 '15 14:09

Ezequiel Miranda


People also ask

How do you write associative array in JavaScript?

An associative array is declared or dynamically createdWe can create it by assigning a literal to a variable. var arr = { "one": 1, "two": 2, "three": 3 }; Unlike simple arrays, we use curly braces instead of square brackets. This has implicitly created a variable of type Object.

Is a map an associative array?

An associative array maps unique keys to values that can be non-unique. An associative array is also called a dictionary, a map, a hash map, or a hash table.

What is associative array in JavaScript with example?

An associative array is an array with string keys rather than numeric keys. Associative arrays are dynamic objects that the user redefines as needed. When you assign values ​​to keys in a variable of type Array, the array is transformed into an object, and it loses the attributes and methods of Array.

How do you map an array in JavaScript?

The syntax for the map() method is as follows: arr. map(function(element, index, array){ }, this); The callback function() is called on each array element, and the map() method always passes the current element , the index of the current element, and the whole array object to it.


2 Answers

You may use Array.prototype.reduce for your task. It allows a return value in the callback function for the next call.

var data = [
        { 'list': 'one', 'item': 1 },
        { 'list': 'one', 'item': 2 },
        { 'list': 'one', 'item': 3 },
        { 'list': 'two', 'item': 1 },
        { 'list': 'two', 'item': 2 }
    ],
    flat = data.reduce(function (r, a) {
        r[a.list] = r[a.list] || [];
        r[a.list].push(a.item);
        return r;
    }, {});

document.write('<pre>' + JSON.stringify(flat, 0, 4) + '</pre>');
like image 90
Nina Scholz Avatar answered Sep 20 '22 20:09

Nina Scholz


To your specific question:

// Let x hold your array of objects.

res={}; // Create an empty object that will hold the answer

x.forEach (function (e) { // Use this function to iterate over each item in the list
    res[e.list] = res[e.list] || [];   // inspired by the Nina Scholz answer below
    res[e.list].push(e.item);   // Append the result to the array
 });
like image 40
Ram Rajamony Avatar answered Sep 17 '22 20:09

Ram Rajamony