Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

189
Views
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
  }
]
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

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"));
about 4 years ago · Juan Pablo Isaza Report

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!