Easy Tutorial
❮ Css Calendar Style 2021 Frontend Learnpath ❯

JavaScript Remove Array Elements

Category Programming Techniques

This article explains how to remove elements from a JavaScript array.

The following example demonstrates a custom method to remove array elements:

Example

Array.prototype.removeByValue = function (val) {
  for (var i = 0; i < this.length; i++) {
    if (this[i] === val) {
      this.splice(i, 1);
      i--;
    }
  }
  return this;
}

var sites = ['apple', 'google', 'tutorialpro', 'taobao'];
sites.removeByValue('google');

console.log(sites);
// -> ['apple', 'tutorialpro', 'taobao']

Alternatively, you can use the array.splice method to achieve the same:

Example

const array = [2, 5, 9];

console.log(array);

const index = array.indexOf(5);
if (index > -1) {
  array.splice(index, 1); // The second parameter is the number of times to remove, set to remove only once
}

// array = [2, 9]
console.log(array);

The following example allows for removing one or multiple elements from an array:

Example

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))

** Click to Share Notes

Cancel

-

-

-

❮ Css Calendar Style 2021 Frontend Learnpath ❯