i have below array of object from API response.i want to push only those object whose id is not repeating and totalTime is 0
for ex – in below JSON, object with id = 4 is repeating twice so i dont want to include
this object into new array, here id = 1 and id = 3 have totaltime is 0, than i want to push this one .
Below is my JSON
const response = [
{
"id": "1",
"oeeCalculations": {
"others": {
"totalTime": 0
}
}
},
{
"id": "2",
"oeeCalculations": {
"others": {
"totalTime": 744
}
}
},
{
"id": "3",
"oeeCalculations": {
"others": {
"totalTime": 0
}
}
},
{
"id": "4",
"oeeCalculations": {
"others": {
"totalTime": 0
}
}
},
{
"id": "4",
"oeeCalculations": {
"others": {
"totalTime": 744
}
}
}
];
Expected output –
const newResponse = [
{
"id": "1",
"oeeCalculations": {
"others": {
"totalTime": 0
}
}
},
{
"id": "3",
"oeeCalculations": {
"others": {
"totalTime": 0
}
}
}
];
I tried below code, but its returning unique lines only..
const values = Object.values(
response.reduce((a, b) => {
if (!a[b.id]) a[b.id] = b
return a
}, {})
)
2
Answers
You need to group the entries by
id
.Filter the
responses
array by matching theid
, the length of theentries
array from each (id
) group is 1 and all the entries must fulfill with theoeeCalculations.others.totalTime
is equal to 0.Demo @ TypeScript Playground
Here is another way to achieve the desired result:
map()
functionfilter()
function, with the help of the previously createdids
listtotalTime
other than0
using thefilter()
functionDemo: