简体   繁体   中英

Removing an element from an array specifying a value in Javascript

I have read this question:

Deleting array elements in JavaScript - delete vs splice

And it appears that both splice and delete require an index of the element in order to remove, so how can I easily find the index when I have the value?

For example if I have an array that looks like this:

["test1", "test2", "test3"]

and I want to remove test2. The process I am using right now, which I'm hoping isn't the correct way to do it, is using $.each checking the value of each element in the array, maintaining a counter through the process (used as the index reference) and if the value is equal to "test2", then I have my index (in form of the counter) and then use splice to remove it.

While the array grows larger, I would imagine this would be a slow process, but what alternatives do I have?

You want to use the splice() function to remove the item, indexOf will find it in the array:

To Find a specific element in the Array: ( to know which to remove )

var index = array.indexOf('test2'); 

Full Example:

var array = ['test1', 'test2', 'test3'];
var value_to_remove = 'test2';
array.splice(array.indexOf(value_to_remove), 1); 

Working Demo

var array = ["test1", "test2", "test3"];
array.splice(array.indexOf("test2"), 1);

indexOf ( source ):
Returns the first index at which a given element can be found in the array, or -1 if it is not present.

You can jQuery's $.inArray and get rid of your $.each loop, and it works cross-browser (unlike Array.indexOf):

var index = $.inArray("test2", ["test1", "test2", "test3"]); // 1

(I realise your question is not tagged with 'jQuery', but you do mention that you're already using an $.each loop).

You find an element by value using Array#indexOf , and then use the resulting index. Note that older browsers may not have it, so you'll want to check to see if it's there and if not add it — here's some code from MDC that does the check and adds the function if it's not there.

if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
        "use strict";
        if (this === void 0 || this === null) {
            throw new TypeError();
        }
        var t = Object(this);
        var len = t.length >>> 0;
        if (len === 0) {
            return -1;
        }
        var n = 0;
        if (arguments.length > 0) {
            n = Number(arguments[1]);
            if (n !== n) { // shortcut for verifying if it's NaN
                n = 0;
            } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
                n = (n > 0 || -1) * Math.floor(Math.abs(n));
            }
        }
        if (n >= len) {
            return -1;
        }
        var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
        for (; k < len; k++) {
            if (k in t && t[k] === searchElement) {
                return k;
            }
        }
        return -1;
    }
}

Note that if you add things to the Array prototype like that, for..in loops that assume they'll only see array indexes (that is, incorrect but common for..in loops) will start having problems because they'll see the string "indexOf" when they're only expecting to see array indexes, see this blog post for details.

underscore.js is a really awesome little library with a lot of good utility functions. In this case #reject would be appropriate.

http://documentcloud.github.com/underscore/#reject

(Although the internal method is of course similar to your manual index lookup and slice/splice).

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