Web Tools Table Maker3schools TranslateImage CompressorFavicon Icon GeneratorCrop & Resize Image
Apu
Apu February 22, 2023 › #Array #HowTo

5 ways to remove specific element from JavaScript array

Removing specific elements from an array is one of the most common tasks that you may encounter when working with JavaScript array. In this article, I'll discuss five different ways to remove specific elements from a JavaScript array.

  1. Remove last element from array using the pop() method. #

    Using the pop() Method: The pop() method removes the last element from an array and returns it as its value. To remove any other element than the last one, you can use splice(). Here's an example:

    <script>
     let arr = [1,2 ,3];
         arr.pop(); // output - [1,2]
    </script>
  2. Remove first element using the shift() method. #

    Using shift() method: The shift() method works like pop(), but instead of removing the last item in an array it removes and returns the first item in your given list. Here's how you can use this function :

    <script>
     let arr = [1,2 ,3];
         arr.shift(); // output - [2,3]
    </script>
  3. Remove specific items using the splice() method. #

    Using splice(): This is probably one of the most useful methods for manipulating arrays because it allows us to add or remove items at any position within an existing array by specifying two parameters.

    <script>
     let arr = [1,2 ,3];
         arr.splice(1,1); // output - [1,3]
    </script>
  4. Using filter() method: The filter() method creates a new array from an existing array, based on a condition that is tested against each element in the original array.

    It takes a callback function as an argument and returns a new array containing only the elements that pass the condition specified by the callback function.

    <script>
      let colors =[ 'red', 'green', 'blue' ];
      let newArr = colors.filter(item => item !== 'green'); 
      console.log(newArr)
    </script>
  5. Delete element from array using indexOf() method. #

    Using the indexOf() method : To remove an item from an array using the indexOf() method, you need to use the splice() method. For example, if you want to remove the item 'green' from the following array, you can use the following code:

    <script>
      let colors =[ 'red', 'green', 'blue' ];
          colors.splice(colors.indexOf('green'), 1)
      console.log(colors)
    </script>
save
listen
AI Answer
Write Your Answer
loading
back
View All