1

John Resig, creator of jQuery created a very handy 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);
};

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

It works great. But I would like to know if it's extendable so that it can take an array of indexes as the first argument?

Otherwise, I will probably make another method that makes use of it:

if (!Array.prototype.removeIndexes) {

    Array.prototype.removeIndexes = function (indexes) {

        var arr = this;

        if (!jQuery)
            throw new ReferenceError('jQuery not loaded');

        $.each(indexes, function (k, v) {

            var index = $.inArray(v, indexes);

            if (index !== -1)
                arr.remove(index);

        });
    };
}

If Array.remove() isn't extendable to fit my needs, what do you think about my other solution above?

2
  • 2
    codereview.stackexchange.com perhaps? Commented Jun 25, 2013 at 8:17
  • Don’t modify objects you don’t own - even if J. Resig does so Commented Jun 25, 2013 at 9:00

3 Answers 3

1

This version should work. It modifies the original array. If you prefer to return a new array without modifying the original, use the commented out initializer of result and add return result at the end of the function.

Array.prototype.removeIndexes = function(indices) { 
  // make sure to remove the largest index first
  indices = indices.sort(function(l, r) { return r - l; });

  // copy the original so it is not changed
  // var result = Array.prototype.slice.call(this);

  // modify the original array
  var result = this;

  $.each(indices, function(k, ix) {
    result.splice(ix, 1);
  });
}

> [0, 1, 2, 3, 4, 5, 6, 7, 8].removeIndexes([4, 5, 1]);
> [0, 2, 3, 6, 7, 8]
Sign up to request clarification or add additional context in comments.

4 Comments

@Johan: this function returns a new array without modifying the original.
Ok, can it be adjusted so that it modifies the actual array that you're using it on?
Thank you. How would splice() handle a -1-index?
It doesn't. ['a', 'b', 'c', 'd', 'e', 'f'].removeIndexes([-1,-3]); returns : [a, b, d, e ] instead of [a, b, c, e ]
1

I think this is what you are looking for (It works with negative index too) :

if (!Array.prototype.removeIndexes) {

    Array.prototype.removeIndexes = function (indexes) {

        var arr = this;

        if (!jQuery) throw new ReferenceError('jQuery not loaded');

        var offset = 0;

        for (var i = 0; i < indexes.length - 1; i++) {
            if (indexes[i] < 0)
                indexes[i] = arr.length + indexes[i];
            if (indexes[i] < 0 || indexes[i] >= arr.length)
                throw new Error('Index out of range');
        }

        indexes = indexes.sort();

        for (var i = 0; i < indexes.length - 1; i++) {
            if (indexes[i + 1] == indexes[i])
                throw new Error('Duplicated indexes');
        }


        $.each(indexes, function (k, index) {
            arr.splice(index - offset, 1);
            offset++;
        });
        return arr;
    };
}

var a = ['a', 'b', 'c', 'd', 'e', 'f'];
var ind = [3, 2, 4];

a.removeIndexes(ind);

console.log(a.join(', '));
// returns : a, b, f 

See fiddle

3 Comments

Thanks. WHat will happen if I pass an index that doesn't exist? Like -1
If you pass a wrong index an error will be throw. You can use negative numbers to select from the end of an array (as the splice function).
Btw, there index is undefined in indexes[i] = arr.length + index;. Did you mean indexes[i] = arr.length + indexes[i];?
0

How about

Array.prototype.remove = function (indexes) {
    if(indexes.prototype.constructor.name == "Array") {
        // your code to support indexes
    } else {
        // the regular code to remove single or multiple indexes
    }

};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.