Home > database >  Sum an array in an array of objects
Sum an array in an array of objects

Time:12-05

I have an array of objects with some car data inside :

const cars = [
{
"id": 1,
"car_make": "Lincoln",
"car_model": "Navigator",
"car_year": 2009,
"data": {
  "rating": 4.9,
  "engines": [3, 4, 5, 6]
}
},
{
"id": 2,
"car_make": "Mazda",
"car_model": "Miata MX-5",
"car_year": 2001,
"data": {
  "rating": 4.1,
  "engines": [1, 2]
}
},]

Next I need to sum all the engines numbers inside the data object in car: So I made the next function but everytime I try to console the array it remains unchanged.

cars.forEach(car => {
car.data.engines.reduce((a,b) => a b,0)
})

console.log(cars);

CodePudding user response:

You need to assign the reduce value to engines again

so change

car.data.engines.reduce((a,b) => a b,0)

to

car.data.engines = car.data.engines.reduce((a,b) => a b,0)

const cars = [
{
"id": 1,
"car_make": "Lincoln",
"car_model": "Navigator",
"car_year": 2009,
"data": {
  "rating": 4.9,
  "engines": [3, 4, 5, 6]
}
},
{
"id": 2,
"car_make": "Mazda",
"car_model": "Miata MX-5",
"car_year": 2001,
"data": {
  "rating": 4.1,
  "engines": [1, 2]
}
}]

cars.forEach(car => {
  car.data.engines = car.data.engines.reduce((a,b) => a b,0)
})

console.log(cars);

CodePudding user response:

Basically the answer to the question should have been an map and create a new array from that old with the data changed.

const newCars = data.map(car => ({
id: car.id,
brand : car.car_make,
engineSum : car.data.engines.reduce((a,b) => a b,0),
})).sort((a,b) => a.engineSum - b.engineSum);

console.log(newCars);
  • Related