Search code examples
javascriptarraysfilterinclude

Filter array by other array


I have two arrays

firstArray = ['10','12'];
secondArray = [{"id":"10", "name":"name 10"}, {"id":"11", "name":"name 11"}, {"id":"12", "name":"name 12"}];

Here I want to delete entries {"id":"11", "name":"name 11"} from my second array because the ID 11 is not in my first array. So the result should be

secondArray = [{"id":"10", "name":"name 10"}, {"id":"12", "name":"name 12"}];

How can I do this ?

I am not sure, the following code can give the correct output

const firstArray = ['10','12'];
let secondArray = [{"id":"10", "name":"name 10"}, {"id":"11", "name":"name 11"}, {"id":"12", "name":"name 12"}];
secondArray = secondArray.filter((o) => firstArray.findIndex((obj)=> obj.id === o.id)!=-1 );
console.log(secondArray);


Solution

  • You could filter with a check if the array includes the wanted id.

    const
        unwanted = ['10', '12'],
        data = [{ id: "10", name: "name 10" }, { id: "11", name: "name 11" }, { id: "12", name: "name 12" }],
        result = data.filter(({ id }) => unwanted.includes(id));
    
    console.log(result);