wezeweze
wezeweze

Reputation: 131

How to check if the id exists in the array of ids javascript

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

Answers (4)

Jonas Wilms
Jonas Wilms

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

qiAlex
qiAlex

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

user663031
user663031

Reputation:

ids.filter(id => items.s.includes(id))

"Filter" the list of ids to those which items.s "includes".

Upvotes: 0

XCS
XCS

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

Related Questions