How can I save data in different arrays depending on specific characteristics?

I have an array with over 50 entries in the form of objects, which I would like to save depending on the Item ID so that I can then apply certain calculations to them. For example, I would like to add up the time of all entries with the Item Id “Las5241Wz”.


Since the array can change dynamically, I can’t analyze it manually. How can I separate the data beforehand according to their Item ID and push them into new arrays? The real Array contains up to 16 objects with the same ID.

var data= []
data = [
  //...objects
{
    itemId: "Las5241Wz", 
    time: 10
  },
  {
    itemId:"Bos1239Zf", 
    time: 11
  },
  {
    itemId:"Las5241Wz", 
    time: 15
  },
  {
    itemId:"Bos1239Zf", 
    time: 21
  }
//...more objets
   ]

The solution for this should look like this:

var Item1 = [
{
    itemId: "Las5241Wz", 
    time: 10
  },
{
    itemId:"Las5241Wz", 
    time: 15
  },
]

var Item2 = [
{
    itemId:"Bos1239Zf", 
    time: 11
  },
{
    itemId:"Bos1239Zf", 
    time: 21
  }
]

Answer

Here is another solution that builds an object with the properties “item1”, “item2” and so on from the given object:

const data = [
  //...objects
{
itemId: "Las5241Wz", 
time: 10
  },
  {
itemId:"Bos1239Zf", 
time: 11
  },
  {
itemId:"Las5241Wz", 
time: 15
  },
  {
itemId:"Bos1239Zf", 
time: 21
  }
//...more objets
   ]

console.log(
Object.values(
data.reduce((o,e)=>((o[e.itemId]=o[e.itemId]||[]).push(e),o),{}))
.reduce((o,c,i)=>(o["item"+(i+1)]=c,o),{})
);

This is a “one-liner” and for that reason not that easy to read. So, probably not the version you would put into your production code.