0

I have an Array[] this.unusedInstruments:

[
    { label: 'one'},
    { label: 'two'},
    { label: 'three'}
]

and a function: (params getting passed in are verified as being 'one', 'two', or 'three'

removeInstrument: function(removedIntrument) {
  var index = this.unusedInstruments.indexOf(removedIntrument);
  delete this.unusedInstruments[index];
},

but I am not getting what I expected. I logged the index, and it is always returning -1 despite the parameter. I am assuming that it is saying that the index doesn't exist, but I guess that means I don't know how to query the parent Array for the indexed Object.

chris Frisina
  • 17,689
  • 19
  • 75
  • 154

2 Answers2

1

.indexOf() will only work if the string is an element of the array you're searching. But in your data, the string is the value of the label property of the element, it's not the element itself. You need to write a loop that drills into the objects and compares with the property.

removeInstrument: function(removedInstrument) {
    for (i = 0; i < this.unusedInstruments.length; i++) {
        if (this.unusedInstruments[i].label == removedInstrument) {
            delete this.unusedInstruments[i];
            break;
        }
    }
}
Barmar
  • 596,455
  • 48
  • 393
  • 495
1

As soon as it's an array - you cannot just delete its elements, otherwise you'll get a holes with undefined value. So you need a bit more intelligent way of doing that:

removeInstrument: function(removedInstrument) {
    var len = this.unusedInstruments.length,
        i;

    var remove = function(arr, from) {
        // Based on John Resig's article (MIT Licensed)
        // http://ejohn.org/blog/javascript-array-remove/

        var rest = arr.slice(from + 1);
        arr.length = from;
        return arr.push.apply(arr, rest);
    };

    for (i = 0; i < len ; ++i) {
        if (this.unusedInstruments[i].label == removedInstrument) {
            remove(this.unusedInstruments, i);
            break;
        }
    }
}

remove() function implementation idea is borrowed at https://stackoverflow.com/a/9815010/251311

Community
  • 1
  • 1
zerkms
  • 230,357
  • 57
  • 408
  • 498