0

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
  }
]
msfld
  • 11
  • 6
  • 1
    Does this answer your question? [How to group by and sum an array of objects?](https://stackoverflow.com/questions/29364262/how-to-group-by-and-sum-an-array-of-objects) – jarmod Nov 09 '21 at 19:31
  • @jarmod Because I have to use several calculations over and above a sum, a solution for storing the individual objects in a new array would be better. I edited the question – msfld Nov 09 '21 at 19:43

2 Answers2

0

Unless you have a performance reason to keep the lists separately, the answer is that you can just store the list of ids as a Set and use array.filter when you want to get the list that is just for that id

Set s = new Set();
for (let i = 0; i < data.length; i++) {
  s.add(data[i].itemId);
}

var createFilterFunc(id) {
  return function(elem) {
    return elem.itemId == id;
  }
}

var items = data.filter (createFilterFunc("Las5241Wz"));
ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
0

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.

Carsten Massmann
  • 26,510
  • 2
  • 22
  • 43