Ask Your Question
1

How can an array be filtered using the values in another array?

asked 2022-03-07 11:00:00 +0000

ladyg gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2021-07-20 07:00:00 +0000

pufferfish gravatar image

To filter an array using the values in another array, you can use the filter() method and pass a function that checks if the value of the first array is included in the second array.

For example:

const arr1 = [1, 2, 3, 4, 5];
const arr2 = [2, 4, 6];

const filteredArray = arr1.filter(value => arr2.includes(value));

console.log(filteredArray); // [2, 4]

In this example, the filter() method checks each value in arr1 and includes() method checks if it's present in arr2. If it is, the value is added to the filteredArray.

Note: This method assumes that both arrays contain only primitive types (numbers, strings, booleans) and does not work with complex objects.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-03-07 11:00:00 +0000

Seen: 12 times

Last updated: Jul 20 '21