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
Here is another way to achieve the desired result:
- Generate an array of all IDs using the
map()
function - Remove all items which have duplicates IDs using the
filter()
function, with the help of the previously createdids
list - Remove all items which have a
totalTime
other than0
using thefilter()
function
const ids = response.map(item => item.id);
const result = response
.filter(item => ids.filter(id => id === item.id).length === 1)
.filter(item => item.oeeCalculations.others.totalTime === 0);
Demo:
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
}
}
}
];
const ids = response.map(item => item.id);
const result = response
.filter(item => ids.filter(id => id === item.id).length === 1)
.filter(item => item.oeeCalculations.others.totalTime === 0);
console.log(result);
One way to achieve this is by using a map
and an object.
- Store object with
id
as key in the map. counter
object keeps track of whichid
has appeared in the array.
const filter = (response) => {
const map = new Map();
const counter = {};
for (let obj of response) {
if (map.has(obj.id)) {
map.delete(obj.id);
continue;
}
if (counter[obj.id]) continue;
obj.oeeCalculations.others.totalTime === 0 && map.set(obj.id, obj);
counter[obj.id] = 1;
}
return Array.from(map.values());
};
Working sample: https://stackblitz.com/edit/vitejs-vite-3pomhd?file=main.js