I have an array
JavaScript
x
9
1
data = [
2
{location: "Phnom Penh", sale: 1000 },
3
{location: "Kandal", sale: 500 },
4
{location: "Takeo", sale: 300 },
5
{location: "Kompot", sale: 700 },
6
{location: "Prey Veng", sale: 100 },
7
{location: "Seam Reap", sale: 800 }
8
];
9
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)
JavaScript
1
11
11
1
data = [
2
{location: "Phnom Penh", sale: 1000 },
3
{location: "Kandal", sale: 500 },
4
{location: "Takeo", sale: 300 },
5
{location: "Kompot", sale: 700 },
6
{location: "Prey Veng", sale: 100 },
7
{location: "Seam Reap", sale: 800 },
8
{location: "Total1", sale: 1300 },
9
{location: "Total2", sale: 900 }
10
];
11
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.
JavaScript
1
27
27
1
const data = [
2
{location: "Phnom Penh", sale: 1000 },
3
{location: "Kandal", sale: 500 },
4
{location: "Takeo", sale: 300 },
5
{location: "Kompot", sale: 700 },
6
{location: "Prey Veng", sale: 100 },
7
{location: "Seam Reap", sale: 800 }
8
];
9
10
function getSales(data, arr) {
11
return data
12
13
// Return the current object where the arr
14
// includes the current object location
15
.filter(el => arr.includes(el.location))
16
17
// Iterate over those returned objects and sum their sales
18
.reduce((acc, { sale }) => acc += sale, 0);
19
}
20
21
const out = [
22
data,
23
{ location: 'Total1', sale: getSales(data, ['Phnom Penh', 'Takeo']) },
24
{ location: 'Total2', sale: getSales(data, ['Prey Veng', 'Seam Reap']) }
25
];
26
27
console.log(out);