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

129
Views
Manipulate objects in an array to include an array of other values in found in sibling objects

I have an array that looks like this (simplified):

[
  {
    name: 'Store1',
    price: ['10'],
    somethingElse: null
  },
  {
    name: 'Store2',
    price: ['5'],
    somethingElse: 6
  },
  {
    name: 'Store2',
    price: ['15'],
    somethingElse: 6
  },
]

I need to turn it into this:

[
  {
    name: 'Store1',
    price: ['10'],
    somethingElse: null
  },
  {
    name: 'Store2',
    price: ['5', '15'],
    somethingElse: 6
  },
]

So for each object where the name is the same, it takes the price's for all of them and puts them in an array, and reduces amount of entries with the same name to one.

It needs to work for a much longer array, and work with many name's.

Let's assume that everything other than the price will be the same in each object that has the same name.

I have tried for too long using array.reduce but with no luck.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

const input = [
  {
    name: 'Store1',
    price: ['10'],
    somethingElse: null
  },
  {
    name: 'Store2',
    price: ['5'],
    somethingElse: 6
  },
  {
    name: 'Store2',
    price: ['15'],
    somethingElse: 6
  },
]

const output = input.reduce((a,c) => {
if(a.find(i => i.name === c.name)) { // Check if 'name' already exist 
    return a.map(el => el.name === c.name ? ({...el, price: [...el.price, ...c.price]}) : el) // updating price for existed name
} else {
    return [...a, c] // no such name, should add to ouput result
}
}, [])

console.log(output)

about 4 years ago · Juan Pablo Isaza Report

0

You can use grouping by hash approach:

const data = [{"name":"Store1","price":["10"],"somethingElse":null},{"name":"Store2","price":["5"],"somethingElse":6},{"name":"Store2","price":["15"],"somethingElse":6}];

const result = Object.values(data.reduce((acc, obj) => {
  acc[obj.name] ??= obj;
  if (!acc[obj.name].price.includes(...obj.price)) 
    acc[obj.name].price.push(...obj.price);

  return acc;
}, {}));

console.log(result);
.as-console-wrapper{min-height: 100%!important; top: 0}

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!