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.
How to Toggle an Element in an Array
To toggle an element in an array, follow these steps:
- Open the Terminal/SSH and type
nodeto start practicing coding. - Check if the given element is in the array using
Array.prototype.includes(). - If the element is in the array, use
Array.prototype.filter()to remove it. - If the element is not in the array, use the spread operator (
...) to push it. - Use the
toggleElementfunction, 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.