'Remove the values from array1 by referring to array2

I have two arrays and I want to remove the values from array1 by referring to array2. The expected result is ["b", "c",];


array1 = ["aa", "bb", "b", "c",];

array2 = [{key: "a", value: "A"}, {key: "b", value: "B"}, {key: "c", value: "C"}, {key: "d", value: "D"}];

I have tried with filter, but it returns [{key: "b", value: "B"}, {key: "c", value: "C"}]


array2.filter((item) => {return array1.includes(item.key)})



Solution 1:[1]

You can do:

array1 = ["aa", "bb", "b", "c",];
array2 = [{key: "a", value: "A"}, {key: "b", value: "B"}, {key: "c", value: "C"}, {key: "d", value: "D"}]; 
array3 = array2.map((item) => (item.key))

remainingItems = array1.filter((item) => array3.includes(item))

The issue with the code you posted is that you're referring to the wrong variables.

// array2 shouldn't be used as you're expecting values from array1
array2.filter((item) => {return array1.includes(item.key)})

// inefficient with repeating maps of array2 but looks closer to your code.
array1.filter((item) => { return array2.map((item) => (item.key)).includes(item) })

Solution 2:[2]

you can do something like this.

const array1 = ["aa", "bb", "b", "c",];

const array2 = [{key: "a", value: "A"}, {key: "b", value: "B"}, {key: "c", value: "C"}, {key: "d", value: "D"}];


const result = array1.filter(a => array2.map(({key}) => key).includes(a))

console.log(result)

As @Nick Parsons noted it probably be more efficent using some like this

const array1 = ["aa", "bb", "b", "c",];

const array2 = [{key: "a", value: "A"}, {key: "b", value: "B"}, {key: "c", value: "C"}, {key: "d", value: "D"}];


const result = array1.filter(a => array2.some(({key}) => key === a))

console.log(result)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2