inwpitrust inwpitrust - 5 months ago 7
Javascript Question

Dynamically create multiples arrays from sorting one array of objects

Given the following array of objects:

var fruits = [
{ type: "banana", number: 20 },
{ type: "apple", number: 2 },
{ type: "pineapple", number: 40 },
{ type: "pineapple", number: 32 },
{ type: "banana", number: 80 },
{ type: "pineapple", number: 24 },
{ type: "apple", number: 64 },
{ type: "apple", number: 12 }
]


How would you sort it by the type key, and dynamically create one new array of objects per type? To obtain something like this:

// new array of bananas:
[
{ type: "banana", number: 20 },
{ type: "banana", number: 80 }
]

// new array of apples:
[
{ type: "apple", number: 2 },
{ type: "apple", number: 64 },
{ type: "apple", number: 12 }
]

// new array of pineapples:
[
{ type: "pineapple", number: 40 },
{ type: "pineapple", number: 32 },
{ type: "pineapple", number: 24 }
]

Answer

You can use Array.prototype.reduce(), Object.hasOwnProperty()

var res = fruits.reduce(function(obj, fruit) {
  if (!obj.hasOwnProperty(fruit.type)) {
    obj[fruit.type] = [fruit]
  } else {
    obj[fruit.type].push(fruit)
  }; 
  return obj
}, {});

console.log(res);