Is there a quick way to remove a specific value from an array in Javascript?

I have an array

var array = ["google","chrome","os","windows","os"];

I want to remove a value "chrome"from an array without the array becoming a string. Is there any way to do this?

+5
source share
6 answers

There is no faster way than finding it and then deleting it. You can do this by using a loop or (in implementations that support it) indexOf. By removing this, you can do it splice.

Real-time example: http://jsbin.com/anuta3/2

var array, index;
array = ["google","chrome","os","windows","os"];
if (array.indexOf) {
  index = array.indexOf("chrome");
}
else {
  for (index = array.length - 1; index >= 0; --index) {
    if (array[index] === "chrome") {
      break;
    }
  }
}
if (index >= 0) {
  array.splice(index, 1);
}
+5
source

This turns it into a convenient function:

function remove_element(array, item) {
  for (var i = 0; i < array.length; ++i) {
    if (array[i] === item) {
      array.splice(i, 1);
      return;
    }
  }
}

var array = ["google", "chrome", "os", "windows", "os"];
remove_element(array, "chrome");

or (for browsers that support indexOf):

function remove_element(array, item) {
  var index = array.indexOf(item);
  if (-1 !== index) {
    array.splice(index, 1);
  }
}

: === !==.

+3

splice Array.

array.splice(1, 1);
+2

The splice () method adds and / or deletes elements to / from the array and returns the deleted element (s).

array.splice(indexOfElement,noOfItemsToBeRemoved);

in your case

   array.splice(1, 1);
+2
source
You may want to remove all of the items that match your string,
or maybe remove items that pass or fail some test expression.
Array.prototype.filter, or a substitute, is quick and versatile: 


var array= ["google","chrome","os","windows","os"],
b= array.filter(function(itm){
    return 'os'!= itm
});
alert(b)
+2
source

You did not indicate whether you want to keep the indices of the remaining elements in your array or not. Based on the fact that you can have undefined array elements, you can do:

var array = ["google","chrome","os","windows","os"];
delete array[1];

array [1] will be undefined.

+1
source

All Articles