'reduce an Object based on DATE and TIME + calculate a VALUE [duplicate]
I have an object and I want to reduce the date and time together and calculate a number.
At the moment I'm trying the following code (but the 'time' value is missing)...
const myObject = [
{
"date": "2023-01-01",
"time": "18:00",
"somevalue": 2
},
{
"date": "2023-01-01",
"time": "18:00",
"somevalue": 5
},
{
"date": "2023-01-02",
"time": "19:00",
"somevalue": 10
},
{
"date": "2023-01-03",
"time": "06:00",
"somevalue": 13
}
];
const all = myObject.reduce( (prev, value) => (
{ ...prev, [value.date]: (prev[value.date] || 0) + value.somevalue } ), {});
// to array
console.log(
Object.entries(all).map( ([key, value]) => ( {date: key, somevalue: value} ) )
);
My question is: How can I add the "time" value. Like this:
[
{
"date": "2023-01-01",
"time": "18:00",
"somevalue": 7
},
{
"date": "2023-01-02",
"time": "19:00",
"somevalue": 10
},
{
"date": "2023-01-03",
"time": "06:00",
"somevalue": 13
}
]
Solution 1:[1]
Maybe something like this?
const myObject = [ { date: "2023-01-01", time: "18:00", somevalue: 2 }, { date: "2023-01-01", time: "18:00", somevalue: 5 }, { date: "2023-01-02", time: "19:00", somevalue: 10 }, { date: "2023-01-03", time: "06:00", somevalue: 13 }];
const output = myObject.reduce((arr, acc) => {
const index = arr.findIndex(({ date, time }) => date === acc.date && time === acc.time); //find duplicated elements by date
if (index > -1) { // if you have duplicated element
arr[index] = {
...arr[index], // merge objects
somevalue: arr[index].somevalue + acc.somevalue // add value
};
} else {
arr = [...arr, acc]; //if no duplicates values, just add to array.
}
return arr;
}, []);
console.log(output)
I use reduce to merge duplicated elements by "date" and add the someValue.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
