简体   繁体   中英

Javascript delete array element from array by value

I have an javascript array and I want to delete an element based on the value of the array, this is my array and this is what I have tried without success.

array = []
array.push (["Mozilla","Firefox",1.10])
index = array.indexOf(["Mozilla","Firefox",1.10])
array.splice(index, 1)

But it doesn't work, any idea¿?

You're trying to compare arrays, which are objects and have unique addresses. Your index variable is -1 .

Try ['Mozilla','Firefox',1.10] === ['Mozilla','Firefox',1.10] in your console, you'll see that just because two arrays have the same values, it doesn't mean they are the same array.

What you need is a deep-equals style of comparison, that checks each value in the array, to see if two arrays have a likeness.

Take a look at lodash's isEqual function for an idea.

Here's a simple looping function:

 function deepIndex(array, comparison) { var i, j; main: for (i = 0; i < array.length; i++) { if (Array.isArray(array[i])) { for (j = 0; j < array[i].length; j++) { if (array[i][j] !== comparison[j]) { continue main; } } return i; } } } var arr = []; arr.push('string', ['Mozilla','Firefox',1.10], 'thing'); var index = deepIndex(arr, ['Mozilla','Firefox',1.10]) console.log(index, arr); arr.splice(index, 1); console.log(arr); 

Take a look at this:

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

This is function, made by the Creator of JQUery. Basically you take the Index of one thing and than it is getting removed

 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); }; //Equals Function taken from: //http://stackoverflow.com/questions/7837456/comparing-two-arrays-in-javascript Array.prototype.equals = function (array) { // if the other array is a falsy value, return if (!array) return false; // compare lengths - can save a lot of time if (this.length != array.length) return false; for (var i = 0, l=this.length; i < l; i++) { // Check if we have nested arrays if (this[i] instanceof Array && array[i] instanceof Array) { // recurse into the nested arrays if (!this[i].equals(array[i])) return false; } else if (this[i] != array[i]) { // Warning - two different object instances will never be equal: {x:20} != {x:20} return false; } } return true; } array = []; array.push (["Mozilla","Firefox",1.10]); array.push (["Microsoft","Spartan",1.0]); array.push (["Safari","Safari",1.4]); index = indexOfArr(array,["Mozilla","Firefox",1.10]); array.remove(index, index); document.getElementById("length").innerHTML = array.length; for(var i = 0; i < array.length; i++){ document.getElementById("elems").innerHTML += "<br>"+array[i]; } function indexOfArr(hay, needle){ for(var i = 0; i < hay.length; i++){ if (hay[i].equals(needle)){ return i; } } return -1; } 
 <span id = "length"></span><br> <span id = "elems">Elements:</span> 

You can use the fiter metodh, instead of indexOf .

Within the callback of that method, you can choose different approaches:

  • Use toString on the arrays and compare the two strings

  • Test for the length and the content, by iterating over the contained elements

  • ... Continue ...

In any case using === will solve the problem, unless the object contained is exactly the same against which you are trying to match. By the same, I mean the same. We are non speaking about having the same content, but to be the same instance.

Loop over your array and check the equality:

array = [];
array.push(["Mozilla", "Firefox", 1.10]);

for (var i = 0; i < array.length; i++) {
    if (arraysEqual(array[i], ["Mozilla", "Firefox", 1.10])) {
        array.splice(i, 1);
    }
}

function arraysEqual(a, b) {
    if (a === b) return true;
    if (a === null || b === null) return false;
    if (a.length != b.length) return false;

    for (var i = 0; i < a.length; ++i) {
        if (a[i] !== b[i]) return false;
    }
    return true;
}

JSFiddle: http://jsfiddle.net/ghorg12110/r67jts35/

Based on this question : How to check if two arrays are equal with JavaScript?

You can do something like this

array = []
array.push (["Mozilla","Firefox",1.10])
tempArray = array[0];
index = tempArray.indexOf("Mozilla","Firefox",1.10)
array.splice(index, 1)

You can build on this if you put for loop instead of hard coding.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM