Skip to content
Advertisement

how to add new calculate array object to existing array

I have an array

data = [
        {location: "Phnom Penh", sale: 1000 },
        {location: "Kandal", sale: 500 },
        {location: "Takeo", sale: 300 },
        {location: "Kompot", sale: 700 },
        {location: "Prey Veng", sale: 100 },
        {location: "Seam Reap", sale: 800 }
      ];

new calculate object :

Total1 = Phnom Penh + Takeo
Total 2 = Prey Veng + Seam Reap

then I want to add these two object to existing array (data)

data = [
        {location: "Phnom Penh", sale: 1000 },
        {location: "Kandal", sale: 500 },
        {location: "Takeo", sale: 300 },
        {location: "Kompot", sale: 700 },
        {location: "Prey Veng", sale: 100 },
        {location: "Seam Reap", sale: 800 },
        {location: "Total1", sale: 1300 },
        {location: "Total2", sale: 900 }
      ];

Anyone please help me to do like this? Thanks

Advertisement

Answer

You could use a bespoke function that filters out the relevant objects, and then calculates their sum sales.

Here the data and an array of the locations is passed into getSales. The required objects are filtered out, and then reduce is used to sum their sales. You can then build a new object using the data from the old object, and adding in the new data.

const data = [
  {location: "Phnom Penh", sale: 1000 },
  {location: "Kandal", sale: 500 },
  {location: "Takeo", sale: 300 },
  {location: "Kompot", sale: 700 },
  {location: "Prey Veng", sale: 100 },
  {location: "Seam Reap", sale: 800 }
];

function getSales(data, arr) {
  return data
    
    // Return the current object where the arr
    // includes the current object location
    .filter(el => arr.includes(el.location))

    // Iterate over those returned objects and sum their sales
    .reduce((acc, { sale }) => acc += sale, 0);
}

const out = [
  ...data,
  { location: 'Total1', sale: getSales(data, ['Phnom Penh', 'Takeo']) },
  { location: 'Total2', sale: getSales(data, ['Prey Veng', 'Seam Reap']) }
];

console.log(out);
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement