Remove Matching Elements From Array

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/AdvancedConceptsGroup -.-> javascript/higher_funcs("`Higher-Order Functions`") subgraph Lab Skills javascript/variables -.-> lab-28587{{"`Remove Matching Elements From Array`"}} javascript/data_types -.-> lab-28587{{"`Remove Matching Elements From Array`"}} javascript/arith_ops -.-> lab-28587{{"`Remove Matching Elements From Array`"}} javascript/comp_ops -.-> lab-28587{{"`Remove Matching Elements From Array`"}} javascript/higher_funcs -.-> lab-28587{{"`Remove Matching Elements From Array`"}} end

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:

  1. Open the Terminal/SSH and type node to start practicing coding.
  2. Use Array.prototype.filter() to find array elements that return truthy values.
  3. Use Array.prototype.reduce() to remove elements using Array.prototype.splice().
  4. 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.

Other JavaScript Tutorials you may like