I have a javascript array of numbers and I add numbers elements in an array using the push() method. 

Is there any simple way to remove a specific item or ​element from a javascript array?

I'm looking for the equivalent of something like removing the item from a javascript array.

array.remove(number);

I have to use core JavaScript. Please give me suggestions in only core javascript to remove items from a javascript array.

array javascript javascript-array 

Nov 17

1 Answers

3 Simple Ways to Remove Irem From A JavaScript Array.

JavaScript arrays allow you to group values and iterate over them. You can add and remove array elements/items in different ways. Unfortunately, there is a simple Javascript Array. remove method.

Instead of a delete method, the JavaScript array has a different variety of ways you can clean array values.

Method 1: 

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

The splice() method adds and/or removes array elements and overwrites the original array. The second parameter splice is the number of items to remove.

const array = [1, 2, 3, 4, 5, 9];
console.log(array);
const index = array.indexOf(5);
if (index > -1) {
  array.splice(index, 1);
}
console.log(array); // return [1, 2, 3, 4, 9]

Method 2:

For the reason of completeness, here are some simple core functions to remove items from a javascript array.

The first custom core function removes only a single occurrence (i.e. removing the first match of 5 from [2,5,9,1,5,8,5])

function removeOnce(arr, value) {
  var index = arr.indexOf(value);
  if (index > -1) {
    arr.splice(index, 1);
  }
  return arr;
}
console.log(removeOnce([2,5,9,1,5,8,5], 5)); // return [2, 9, 1, 5, 8, 5]

the second custom core function removes all occurrences from javascript array:

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

Method 3:

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;
}

Removing Javascript Array items is important to managing your data. There is not a single 'remove' method available, but there are different methods and techniques you can use to purge unwanted array items.

answered Dec 20


Login and Submit Your Answer
Browse other questions tagged  array  javascript  javascript-array or ask your own question.