Home > Web Front-end > JS Tutorial > How to Filter an Array from Elements of Another Array in JavaScript?

How to Filter an Array from Elements of Another Array in JavaScript?

Susan Sarandon
Release: 2024-11-17 11:11:02
Original
936 people have browsed it

How to Filter an Array from Elements of Another Array in JavaScript?

Filtering an Array Using the Filter Function

Filtering an array from all elements of another array is a common programming task. In JavaScript, one would typically use the .filter() function to accomplish this. However, understanding how to provide the function with the values to remove can be challenging.

Consider the following scenario:

var array = [1,2,3,4];
var anotherOne = [2,4];
var filteredArray = array.filter(myCallback);
// filteredArray should now be [1,3]


function myCallBack(){
    return element ! filteredArray; 
    //which clearly can't work since we don't have the reference <,< 
}
Copy after login

In the example above, the myCallBack function attempts to return an element that is not present in the filtered array, but this logic won't work because filteredArray is not yet defined when the function is called.

Using the Filter Function

To filter an array using the filter() function, one should pass a callback function that returns true for elements that should be included in the filtered array and returns false for elements that should be removed. The filtered array is then created by applying the callback function to each element of the original array.

In the case of filtering an array from all elements of another array, the callback function can be simplified, as shown in the following code:

var arr1 = [1,2,3,4],
    arr2 = [2,4],
    res = arr1.filter(item => !arr2.includes(item));
console.log(res); // Output: [1,3]
Copy after login

Here, the filter() function iterates through arr1 and calls the callback function for each element. The callback function, item => !arr2.includes(item), returns true for elements that are not present in arr2 and false otherwise. As a result, the filtered array res contains only the elements [1,3] that are not in arr2.

The above is the detailed content of How to Filter an Array from Elements of Another Array in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template