Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I remove a specific item from an array?

I have an array of numbers and I'm using the .push() method to add elements to it.

Is there a simple way to remove a specific element from an array?

I'm looking for the equivalent of something like:

array.remove(number); 

I have to use core JavaScript. Frameworks are not allowed.

like image 806
Walker Avatar asked Apr 23 '11 22:04

Walker


People also ask

How do I remove an item from an array by value?

To remove an item from a given array by value, you need to get the index of that value by using the indexOf() function and then use the splice() function to remove the value from the array using its index.

How do you remove one property from an array of objects?

To remove a property from all objects in an array: Use the Array. forEach() method to iterate over the array. On each iteration, use the delete operator to delete the specific property. The property will get removed from all objects in the array.


1 Answers

Find the index of the array element you want to remove using indexOf, and then remove that index with splice.

The splice() method changes the contents of an array by removing existing elements and/or adding new elements.

const array = [2, 5, 9];  console.log(array);  const index = array.indexOf(5); if (index > -1) {   array.splice(index, 1); // 2nd parameter means remove one item only }  // array = [2, 9] console.log(array); 

The second parameter of splice is the number of elements to remove. Note that splice modifies the array in place and returns a new array containing the elements that have been removed.


For the reason of completeness, here are functions. The first function removes only a single occurrence (i.e. removing the first match of 5 from [2,5,9,1,5,8,5]), while the second function removes all occurrences:

function removeItemOnce(arr, value) {   var index = arr.indexOf(value);   if (index > -1) {     arr.splice(index, 1);   }   return arr; }  function removeItemAll(arr, value) {   var i = 0;   while (i < arr.length) {     if (arr[i] === value) {       arr.splice(i, 1);     } else {       ++i;     }   }   return arr; } // Usage console.log(removeItemOnce([2,5,9,1,5,8,5], 5)) console.log(removeItemAll([2,5,9,1,5,8,5], 5))

In TypeScript, these functions can stay type-safe with a type parameter:

function removeItem<T>(arr: Array<T>, value: T): Array<T> {    const index = arr.indexOf(value);   if (index > -1) {     arr.splice(index, 1);   }   return arr; } 
like image 170
31 revs, 26 users 13% Avatar answered Oct 21 '22 10:10

31 revs, 26 users 13%