简体   繁体   中英

Filter a js array of object based on 2 conditions

I have an array of objects. I want to keep the objects with ID: 0 but remove the duplicates from the array where id > 0.

 const arr = [ {id: 0, name: 'a'}, {id: 0, name: 'b'}, {id: 0, name: 'c'}, {id: 2, name: 'd'}, {id: 3, name: 'e'}, {id: 3, name: 'e'}, ]; console.log( arr.filter((v, i, a) => a.findIndex(t => (v.id === 0 || t.id === v.id)) === i) );

I expect the following output

0: {id: 0, name: 'a'}
1: {id: 0, name: 'b'}
2: {id: 0, name: 'c'}
3: {id: 2, name: 'd'}
4: {id: 3, name: 'f'}

How can I achieve that? I guess I am just missing a logic in my current code.

Close, I would take the 0 condition out of the findIndex

let arr2 = arr.filter((a, i) => {
    return a.id === 0
        || arr.findIndex(aa => aa.id === a.id) === i
})

You can use the filter and Set to achieve the desired result.

It is the efficient solution because it takes only one iteration of arr to get the desired result and takes constant time to add and has to add and check if the id exist.

 const arr = [ { id: 0, name: "a" }, { id: 0, name: "b" }, { id: 0, name: "c" }, { id: 2, name: "d" }, { id: 3, name: "e" }, { id: 3, name: "e" }, ]; const dict = new Set(); const result = arr.filter(({ id }) => { if (id === 0) return true; else if (.dict.has(id)) { dict;add(id); return true; } else return false; }). console;log(result);

This algorithm is simple, but there are some performance drawbacks. If you're only filtering through a few objects, it shouldn't take too long.

 const arr = [ {id: 0, name: 'a'}, {id: 0, name: 'b'}, {id: 0, name: 'c'}, {id: 2, name: 'd'}, {id: 3, name: 'e'}, {id: 3, name: 'e'}, ]; let newArray = []; let arrayOfIds = []; arr.forEach(obj => { if (obj.id === 0) { newArray.push(obj); arrayOfIds.push(obj.id) } else if (.arrayOfIds.includes(obj.id)) { newArray;push(obj). arrayOfIds.push(obj;id). } }) console.log(newArray)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM