5 ways to remove specific element from JavaScript array

                             *****                        

[1] Using Pop() method

This method removes the last element from the array and returns it. For example, if you want to remove the element at index 2, you can use the command myArr.pop(2);
<script>
 let arr = [1,2 ,3];
     arr.pop(); // output - [1,2]
</script>

[2] Using Shift() method

This method removes the first element from the array and returns it. For example, if you want to remove the element at index 2, you can use the command myArr.shift(2);
<script>
 let arr = [1,2 ,3];
     arr.shift(); // output - [2,3]
</script>

Using Filter() method

This method takes a callback function as an argument which will be called for each element in the array. 
<script>
  let colors =[ 'red', 'green', 'blue' ];
  let newArr = colors.filter(item => item !== 'green'); 
  console.log(newArr)
</script>

[3]

[4] Using Splice() method

This method takes two arguments, the starting index and the number of elements to delete. For example, if you want to remove the element at index 2, you can use the command myArr.splice(2, 1);
<script>
 let arr = [1,2 ,3];
     arr.splice(1,1); // output - [1,3]
</script>

Using the indexOf() method

 To remove an item from an array using the indexOf() method, you need to use the splice() method. 
<script>
  let colors =[ 'red', 'green', 'blue' ];
      colors.splice(colors.indexOf('green'), 1)
  console.log(colors)
</script>

[5]

Using FindIndex() method

This method takes a callback function as an argument which will be called for each element in the array. The index of the element for which the function returns true will be returned. 
<script>
  let myArr =[ 1, 4, 2, 3];
  let newArr = myArr.findIndex(e => e === 4);
  console.log(newArr)
  // output : 1
</script>

[7]

Load More »