简体   繁体   中英

How to check if an id (inside a list of ids) exists in an array of objects with ids?

List1:

[1,2,3,4]

List2:

[{id:1,name:hi},{id:3,name:hi},{id:5,name:hi}]

How can I check which items from List1 is missing from List2?

You can do something like this with help of map() and filter()

 var list1 = [1, 2, 3, 4], list2 = [{ id: 1, name: 'hi' }, { id: 3, name: 'hi' }, { id: 5, name: 'hi' }]; // get array of id's var ids = list2.map(function(v) { return v.id; }) // get missing elements var miss = list1.filter(function(v) { // check element in id's array return ids.indexOf(v) == -1; }); document.write('<pre>' + JSON.stringify(miss, null, 3) + '</pre>'); 


Using ES6 arrow function

 var list1 = [1, 2, 3, 4], list2 = [{ id: 1, name: 'hi' }, { id: 3, name: 'hi' }, { id: 5, name: 'hi' }]; // get array of id's var ids = list2.map(v => v.id); // get missing elements var miss = list1.filter(v => ids.indexOf(v) == -1); document.write('<pre>' + JSON.stringify(miss, null, 3) + '</pre>'); 

Use Array.prototype.filter

 var list1 = [1,2,3,4]; var list2 = [{id:1,name:'hi'},{id:3,name:'hi'},{id:5,name:'hi'}]; var t = list2.map(e => e.id); // get all 'ids' from 'list2' var result = list1.filter(e => t.indexOf(e) == -1); document.write(JSON.stringify(result)); 

I would try to reduce list2 to array of missing ids. Maybe like this:

 var data = [{id: 1, name: 'hi'}, {id: 3, name: 'hi'}, {id: 5, name: 'hi'}] var ids = [1, 2, 3, 4] var missing = data.reduce(function(prev, curr) { return prev.filter(function(id) { return id !== curr.id }) }, ids.slice()) document.write(missing) 

A solution with linear complexity for sorted arrays.

 var list1 = [1, 2, 4, 30], list2 = [{ id: 1, name: 'hi' }, { id: 3, name: 'hi' }, { id: 5, name: 'hi' }], missing = list1.filter(function (a) { while (list2[this.index] && list2[this.index].id < a) { this.index++; } return !list2[this.index] || list2[this.index].id !== a; }, { index: 0 }); document.write('<pre>' + JSON.stringify(missing, 0, 4) + '</pre>'); 

Combine Array methods filter and some :

var list1 = [1,2,3,4];
var list2 = [{id:1,name:'hi'},{id:3,name:'hi'},{id:5,name:'hi'}];
return list2.filter(function(o) {
    return !list1.some(function(id) { return o.id === id; })
})

which yields the objects from list2 whose ids are not in list1 .

The converse, as I saw many people post, is this:

return list1.filter(function(id) {
     return !list2.some(function(o) { return o.id === id; });
});

which yields the ids from list1 that do not have corresponding objects in list2

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