-2
How to mount an array that sums the values in 2 subtotals?
I used the .filter
, .map
and .reduce
to add the values but does not work with more than one category in the same array.
var data = [
{ name: 'test1', day: '05/18', company:'1', total_price: 3 },
{ name: 'test4', day: '05/18', company:'1', total_price: 7 },
{ name: 'test2', day: '05/18', company:'2', total_price: 13.6 },
{ name: 'test3', day: '06/18', company:'1', total_price: 8 },
{ name: 'test3', day: '06/18', company:'2', total_price: 15 },
{ name: 'test4', day: '07/18', company:'2', total_price: 8 },
];
const sum = (a, b) => a+b;
const uniqueCategories = (array) => [...new Set(array.map(item => item.day))];
const chartData = uniqueCategories(data).map(day => [
day,
data
.filter(item => item.day===day)
.map(item => item.total_price)
.reduce(sum)
]);
chartData.splice(0, 0, ["Day","$"])
console.log(chartData)
Return:
chartData= [
["Day", "$"],
["05/18", 23.6],
["06/18", 23],
["07/08", 8]
]
It was expected:
chartData= [
["Day", "1", "2"],
["05/18", 10, 13.6],
["06/18", 8, 15],
["07/08", 0, 8]
]
Read What a mistake I made asking my question?. You need to include more details in your question, such as: what is the expected result?
– Lucas Samuel