Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses and challenges
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

51
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.

7 months 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)

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

7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs