Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

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

>Solution :

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"));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading