Home > Software engineering >  How can I save data in different arrays depending on specific characteristics?
How can I save data in different arrays depending on specific characteristics?

Time:11-10

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
  }
]

CodePudding user response:

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"));

CodePudding user response:

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),{})
);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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.

  • Related