Mauro74
Mauro74

Reputation: 4826

Javascript transform array into grouped object by value

I have an array:

["car1-coupe", "car2-convertible", "car2-hatchback", "car2-estate", "car3-hatchback", "car3-estate"] 

The array can have different sets of cars, and I want to turn it into something like this:

[{
    car1: ["car1-coupe"]
},{
    car2: ["car2-convertible", "car2-hatchback", "car2-estate"]
},{
    car3: ["car3-hatchback", "car3-estate"]
}]

How can I do this in JavaScript or Underscore?

Upvotes: 1

Views: 66

Answers (3)

Antoine Combes
Antoine Combes

Reputation: 1454

var array = ["car1-coupe", "car2-convertible", "car2-hatchback", "car2-estate", "car3-hatchback", "car3-estate"];

var result = {};

for (var i = 0; i < array.length; i++) {
  var key = array[i].split('-')[0]; // The car we're interested in
  if (result[key]) { // Check if this car has already been initialized
    result[key].push(array[i]); //add this model to the list
  } else {
    result[key] = [array[i]]; // initialize the array with the first value
  }
}

console.log(result);
/*will return :
{
  car1: ["car1-coupe"],
  car2: ["car2-convertible", "car2-hatchback", "car2-estate"],
  car3: ["car3-hatchback", "car3-estate"]
}
*/

Upvotes: 0

Fyre
Fyre

Reputation: 1180

var  myObj = {}, myArr = [];
for( var i = 0; i < arr.length; i+=1) {
      var key = arr[i].split("-")[0];
      myObj = {};
      myObj[key] = [];
      for( var j = i; j < arr.length; j+=1 ) {
            if( key === arr[j].split("-")[0])
                myObj[key].push(arr[j]);
      }
      myArr.push(myObj);
}

I think this can be done simply with this way. One loop to get the key and another inner loop to get all values of this key.

Upvotes: -1

Cerbrus
Cerbrus

Reputation: 72857

So, assuming an array like this:

var a = ["car1-coupe", "car2-convertible", "car2-hatchback", "car2-estate", "car3-hatchback", "car3-estate"];

You can do this:

var b = a.reduce(function(prev, curr){
    var car = curr.split('-')[0]; // "get" the current car
    prev[car] = prev[car] || [];  // Initialize the array for the current car, if necessary.
    prev[car].push(curr);         // Add the current item to the array.
    return prev;
}, {});

This will return the following object:

{
    car1: ["car1-coupe"],
    car2: ["car2-convertible", "car2-hatchback", "car2-estate"],
    car3: ["car3-hatchback", "car3-estate"]
}

Upvotes: 2

Related Questions