javascript tutorial - [Solved-5 Solutions] Deleting array elements in JavaScript - delete vs splice - javascript - java script - javascript array



Problem:

How to delete array elements in JavaScript?

Solution 1:

myArray = ['a', 'b', 'c', 'd'];

delete myArray[1];
//  or
myArray.splice (1, 1);

click below button to copy the code. By JavaScript tutorial team

Solution 2:

delete will delete the object property, but will not reindex the array or update its length. This makes it appears as if it is undefined:

> myArray = ['a', 'b', 'c', 'd']
  ["a", "b", "c", "d"]
> delete myArray[0]
  true
> myArray
  [undefined, "b", "c", "d"]
Splice(start, deleteCount) <https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/splice> actually removes the element from the array:
> myArray = ['a', 'b', 'c', 'd']
  ["a", "b", "c", "d"]
> myArray.splice(0, 2)
  ["a", "b"]
> myArray
  ["c", "d"]

click below button to copy the code. By JavaScript tutorial team

Solution 3:

Array.remove method that I always use it in my projects.

// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};
click below button to copy the code. By JavaScript tutorial team

and here's some examples of how it could be used:

// Remove the second item from the array
array.remove(1);
// Remove the second-to-last item from the array
array.remove(-2);
// Remove the second and third items from the array
array.remove(1,2);
// Remove the last and second-to-last items from the array
array.remove(-2,-1);

click below button to copy the code. By JavaScript tutorial team

Solution 4:

The length of the array won't change. Splice removes the object and shortens the array. The following code will display "a", "b", "undefined", "d"

myArray = ['a', 'b', 'c', 'd']; delete myArray[2];

for (var count = 0; count < myArray.length; count++) {
    alert(myArray[count]);
}
click below button to copy the code. By JavaScript tutorial team

Whereas this will display "a", "b", "d"

myArray = ['a', 'b', 'c', 'd']; myArray.splice(2,1);

for (var count = 0; count < myArray.length; count++) {
    alert(myArray[count]);
}

click below button to copy the code. By JavaScript tutorial team

Solution 5:

var items = ['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd'];

while (items.indexOf('c') !== -1) {
  items.splice(items.indexOf('c'), 1);
}

console.log(items); // ["a", "b", "d", "a", "b", "d"]

items = ['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd'];

while (items.indexOf('c') !== -1) {
  delete items[items.indexOf('c')];
}

console.log(items); // ["a", "b", undefined, "d", "a", "b", undefined, "d"]

click below button to copy the code. By JavaScript tutorial team

Related Searches to javascript tutorial - Deleting array elements in JavaScript - delete vs splice