aDoN
aDoN

Reputation: 1951

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¿?

Upvotes: 0

Views: 225

Answers (5)

Anders Anderson
Anders Anderson

Reputation: 433

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>

Upvotes: 2

Varun
Varun

Reputation: 597

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.

Upvotes: 1

Magicprog.fr
Magicprog.fr

Reputation: 4100

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?

Upvotes: 1

Oka
Oka

Reputation: 26345

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

Upvotes: 2

skypjack
skypjack

Reputation: 50540

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.

Upvotes: 1

Related Questions