Toggle Element in Array

JavaScriptJavaScriptBeginner
Practice Now

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

Introduction

In this lab, we will explore how to toggle an element in an array using JavaScript. The toggleElement() function allows you to remove an element from an array if it's already included in it or add the element to the array if it's not already present. This lab will help you understand how to use the includes() and filter() methods in combination with the spread operator to efficiently toggle array elements.


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-28664{{"`Toggle Element in Array`"}} javascript/data_types -.-> lab-28664{{"`Toggle Element in Array`"}} javascript/arith_ops -.-> lab-28664{{"`Toggle Element in Array`"}} javascript/comp_ops -.-> lab-28664{{"`Toggle Element in Array`"}} javascript/higher_funcs -.-> lab-28664{{"`Toggle Element in Array`"}} javascript/spread_rest -.-> lab-28664{{"`Toggle Element in Array`"}} end

How to Toggle an Element in an Array

To toggle an element in an array, follow these steps:

  1. Open the Terminal/SSH and type node to start practicing coding.
  2. Check if the given element is in the array using Array.prototype.includes().
  3. If the element is in the array, use Array.prototype.filter() to remove it.
  4. If the element is not in the array, use the spread operator (...) to push it.
  5. Use the toggleElement function, which accepts an array and a value, to toggle the element in the array.
const toggleElement = (arr, val) =>
  arr.includes(val) ? arr.filter((el) => el !== val) : [...arr, val];

toggleElement([1, 2, 3], 2); // [1, 3]
toggleElement([1, 2, 3], 4); // [1, 2, 3, 4]

By following these steps, you can easily toggle an element in an array using JavaScript.

Summary

Congratulations! You have completed the Toggle Element in Array lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like