JavaScript

How to remove a specific item from an array in Javascript

In this tutorial, we are going to see different methods to remove an element from an array either by using the splice method or the filter method. The splice() method modifies the contents of an array by removing existing elements and/or adding new elements. While the filter() method does not modify the original array.
 

How to remove a specific item from an array in Javascript

First, find the index of the item you want to delete, then delete it with splice().

var arr = [3, 6, 8];

var index = arr.indexOf(6);
if (index > -1) {
  array.splice(index, 1);
}

console.log(arr);

Output:

[3, 8]

 

How to remove a specific item from an array using ECMAScript 6:

In the example below, we use the array.filter(...) function to remove unwanted elements from the array. This function does not change the original table and creates a new one. If your browser does not support this feature, try using Mozilla’s polyfill filter.

let nbr = 6

var arr = [3, 6, 8];

arr = arr.filter(item => item !== nbr)

console.log(arr)

Output:

[3, 8]
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *