简体   繁体   中英

Remove specific elements from array

i got this code :

Object.defineProperty(Array.prototype, "remove", {
    enumerable: false,
    value: function (item) {
        var removeCounter = 0;

        for (var index = 0; index < this.length; index++) {
            if (this[index] === item) {
                this.splice(index, 1);
                removeCounter++;
                index--;
            }
        }

        return removeCounter;
    }
});

And i try to remove from array specific elements with this code line :

var itemsRemoved = finalArray.remove(getBack);

But if i do console.log() it return 0 elements removed while my variable getBack is equal with 0 or other number and in array getBack value exists.

Use item.indexOf(this[index]) instead of this[index] === item .

Why? item is an Array and not a single Value:

Object.defineProperty(Array.prototype, "remove", {
    enumerable: false,
    value: function (item) {
        var removeCounter = 0;

        for (var index = 0; index < this.length; index++) {
            console.log(this[index], item);
            if (item.indexOf(this[index]) > -1) {
                this.splice(index, 1);
                removeCounter++;
                index--;
            }
        }

        return removeCounter;
    }
});

See this thread about object comparison in js

A quick way to achieve it :

Object.defineProperty(Array.prototype, "remove", {
    enumerable: false,
    value: function (item) {
        var removeCounter = 0;

        for (var index = 0; index < this.length; index++) {
            if (JSON.stringify(this[index]) === JSON.stringify(item)) {
                this.splice(index, 1);
                removeCounter++;
                index--;
            }
        }

        return removeCounter;
    }
});

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