1

I have 2 arrays and I want to filter one of the arrays with another array.

2 arrays designed like this

array1= [{id:23},{id:11},{id:435}]

array2= [23, 435, 5]

I want to check and get items only if id of objects inside array1 is equal to one of the ids (string values ) in array2

I found a simple solution like this

var filtered=[1,2,3,4].filter(function(e){return this.indexOf(e)<0;},[2,4]);

but my case is a bit different, I dont know how to make return part, how can I get indexes of each array ?

var filtered=array1.filter(function(e){return e.id === ??},array2);
2
  • please add the wanted result. why do you need to use this? Commented May 16, 2018 at 18:06
  • This answer explains about filtering. Look for more complex comparer Commented May 16, 2018 at 18:17

2 Answers 2

1

You could just look up the index by using the id property.

var array1 = [{ id: 23 }, { id: 11 }, { id: 435 }],
    array2 = [23, 435, 5],
    filtered = array1.filter(function (o) {
        return array2.indexOf(o.id) > -1;
    });
    
console.log(filtered);

ES6

var array1 = [{ id: 23 }, { id: 11 }, { id: 435 }],
    array2 = [23, 435, 5],
    filtered = array1.filter(({ id }) => array2.includes(id));
    
console.log(filtered);

Sign up to request clarification or add additional context in comments.

1 Comment

thanks but it only worked when I make it > -1 instead of < 0 I think you thought it reverse
0

You can use .filter and essentially check if the object id exists in array2. There are several ways to do that including .find and .findIndex. I would use .some which returns true if a single match is found.

array1.filter(obj => array2.some(id => id === obj.id));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.