Filter Out Matching Array Elements

JavaScriptJavaScriptBeginner
Practice Now

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

Introduction

In this lab, we will be exploring how to filter out matching array elements using JavaScript. We will learn how to use the Array.prototype.includes() method to find values to exclude and how to implement the Array.prototype.filter() method to create a new array that excludes these values. By the end of this lab, you will have a solid understanding of how to filter out specific elements in an array using 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`") javascript/AdvancedConceptsGroup -.-> javascript/spread_rest("`Spread and Rest Operators`") subgraph Lab Skills javascript/variables -.-> lab-28298{{"`Filter Out Matching Array Elements`"}} javascript/data_types -.-> lab-28298{{"`Filter Out Matching Array Elements`"}} javascript/arith_ops -.-> lab-28298{{"`Filter Out Matching Array Elements`"}} javascript/comp_ops -.-> lab-28298{{"`Filter Out Matching Array Elements`"}} javascript/higher_funcs -.-> lab-28298{{"`Filter Out Matching Array Elements`"}} javascript/spread_rest -.-> lab-28298{{"`Filter Out Matching Array Elements`"}} end

How to Filter Out Matching Array Elements in JavaScript

To filter out elements in a JavaScript array that have one or more specified values, follow these steps:

  1. Open the Terminal or SSH and type node to start practicing coding.
  2. Use the Array.prototype.includes() method to find the values to exclude.
  3. Use the Array.prototype.filter() method to create a new array with the excluded elements.

Here is an example code snippet:

const without = (arr, ...args) => arr.filter((v) => !args.includes(v));

without([2, 1, 2, 3], 1, 2); // [3]

In this example, the without function takes an array arr and one or more arguments args. The function uses the filter() method to create a new array that excludes any elements that match any of the specified values in args. The includes() method is used to check if the value is in args. Finally, the function returns the new array with the excluded elements.

Summary

Congratulations! You have completed the Filter Out Matching Array Elements lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like