Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
154 views
in Technique[技术] by (71.8m points)

javascript - Filter Array Not in Another Array

Need to filter one array based on another array. Is there a util function in knock out ? else i need to go with javascript

First :

var obj1 = [{
    "visible": "true",
    "id": 1
}, {
    "visible": "true",
    "id": 2
}, {
    "visible": "true",
    "id": 3
}, {
    "Name": "Test3",
    "id": 4
}];

Second :

var obj2 = [ 2,3]

Now i need to filter obj1 based on obj2 and return items from obj1 that are not in obj2 omittng 2,3 in the above data (Comparison on object 1 Id)

output:

[{
    "visible": "true",
    "id": 1
}, {
    "Name": "Test3",
    "id": 4
}];
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can simply run through obj1 using filter and use indexOf on obj2 to see if it exists. indexOf returns -1 if the value isn't in the array, and filter includes the item when the callback returns true.

var arr = obj1.filter(function(item){
  return obj2.indexOf(item.id) === -1;
});

With newer ES syntax and APIs, it becomes simpler:

const arr = obj1.filter(i => !obj2.includes(i.id))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...