Reputation: 131
I have an object like:
item: {
b: null
c: "asd"
i: 10
q: 10
s: Array [237,241]}
Also I have an array of ids:
var ids = [237, 238, 239, 240, 242, 243...]
I dont know how to check if above ids exist in s, and then save those items to new array or object
for (var key in items) {
for (var i in items[key].s) {
//...
}
}
Upvotes: 0
Views: 39387
Reputation: 138247
if(items.s.some(el => ids.includes(el))) alert("wohoo");
Simply check if some of the items ids is included in the ids array. Or using a for loop:
for(var i = 0; i < items.s.length; i++){
if( ids.includes( items.s[i] )){
alert("wohoo");
}
}
Upvotes: 9
Reputation: 4346
var item = {
b: null,
c: "asd",
i: 10,
q: 10,
s: [237,241]
}
var ids = [237, 238, 239, 240, 242, 243];
// way number 1
for(var i = 0; i < item.s.length; i++){
if( ~ids.indexOf(item.s[i])){
console.log(item.s[i]);
}
}
//way number 2
var myArr = item.s.filter(x => ~ids.indexOf(x));
console.log(myArr);
Upvotes: 1
Reputation:
ids.filter(id => items.s.includes(id))
"Filter" the list of ids
to those which items.s
"includes".
Upvotes: 0
Reputation: 28137
You can use Array.filter
and Array.indexOf
. I assume that you are not using any code transpiler, si I recommend using indexOf
instead of includes
as it has better browser support.
var foundIds = item.s.filter(x => ids.indexOf(x) !== -1);
// foundIds now contains the list of IDs that were matched in both `ids` and `item.s`
var item = {
b: null,
c: "asd",
i: 10,
q: 10,
s: [237,241]
}
var ids = [237, 238, 239, 240, 242, 243];
var foundIds = item.s.filter(x => ids.indexOf(x) !== -1);
console.log(foundIds);
Upvotes: 2