Reject Non-Matching Values

JavaScriptJavaScriptBeginner
Practice Now

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

Introduction

In this lab, we will explore how to filter an array's values based on a predicate function, returning only values for which the predicate function returns false. We will use Array.prototype.filter() in combination with the predicate function to achieve this. By the end of this lab, you will have a good understanding of how to implement this technique in your JavaScript code.


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-28580{{"`Reject Non-Matching Values`"}} javascript/data_types -.-> lab-28580{{"`Reject Non-Matching Values`"}} javascript/arith_ops -.-> lab-28580{{"`Reject Non-Matching Values`"}} javascript/comp_ops -.-> lab-28580{{"`Reject Non-Matching Values`"}} javascript/higher_funcs -.-> lab-28580{{"`Reject Non-Matching Values`"}} javascript/spread_rest -.-> lab-28580{{"`Reject Non-Matching Values`"}} end

Filtering Array Values

To filter an array based on a predicate function and return only values for which the predicate function returns false, follow these steps:

  1. Use Array.prototype.filter() in combination with the predicate function, pred.
  2. The filter method will return only the values for which the predicate function returns false.
  3. To reject non-matching values, pass the predicate function and the array to the reject() function.
const reject = (pred, array) => array.filter((...args) => !pred(...args));

Here are some examples of how to use the reject() function:

reject((x) => x % 2 === 0, [1, 2, 3, 4, 5]); // [1, 3, 5]
reject((word) => word.length > 4, ["Apple", "Pear", "Kiwi", "Banana"]);
// ['Pear', 'Kiwi']

By following these steps, you can easily filter an array based on a predicate function and reject non-matching values.

Summary

Congratulations! You have completed the Reject Non-Matching Values lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like