Introduction
In this lab, we will be exploring how to remove matching elements from an array using JavaScript. We will be using the Array.prototype.filter() method to find the elements that match the given condition and Array.prototype.reduce() method to remove them from the original array. By the end of this lab, you will have a better understanding of how to manipulate arrays in JavaScript.
Removing Matching Elements from an Array
To remove specific elements from an array based on a given condition, you can use the remove function. This function mutates the original array by removing elements for which the given function returns false.
Here are the steps to use the remove function:
- Open the Terminal/SSH and type
nodeto start practicing coding. - Use
Array.prototype.filter()to find array elements that return truthy values. - Use
Array.prototype.reduce()to remove elements usingArray.prototype.splice(). - The callback function is invoked with three arguments (value, index, array).
const remove = (arr, func) =>
Array.isArray(arr)
? arr.filter(func).reduce((acc, val) => {
arr.splice(arr.indexOf(val), 1);
return acc.concat(val);
}, [])
: [];
Here's an example of using the remove function:
remove([1, 2, 3, 4], (n) => n % 2 === 0); // [2, 4]
This will return a new array with the removed elements.
Summary
Congratulations! You have completed the Remove Matching Elements From Array lab. You can practice more labs in LabEx to improve your skills.