简体   繁体   中英

Remove array elements by index

I seem to be having a brain-freeze and am unable to remove JS array elements by index. Is there something fundamentally idiotic in the below?

var els;
[0, 1, 3]
0: 0
1: 1
2: 3


["Colour", "Font", "Icon", "Line 1"]
0: "Colour"
1: "Font"
2: "Icon"
3: "Text"

All I want to do is remove the elements from the array using index positions 0, 1 and 3 (in this example) - however, when I try this using splice, it messes up the indexes.

See:

els.each(function(key, val) {
            console.log(key);
            req-fields.splice(key,1);
        });

Try something like this

function removeIndex(array, index) {
    delete array[index];
    array = array.filter(function(element) {
        return element != undefined
    });
    return array;
}

Example

removeIndex([1,4,7,13,41,16],3);
=> [1,4,7,41,16]

Explanation

To delete an element from an array, you use the delete keyword. This will make the value at that index undefined . You then need to filter the array, and remove undefined elements.

You can adjust the index of the splice for every splicing action.

 var fields = ["Colour", "Font", "Icon", "Line 1"], els = [0, 1, 3]; els.forEach(function (val, i) { fields.splice(val - i, 1); }); document.write('<pre>' + JSON.stringify(fields, 0, 4) + '</pre>'); 

The issue is when you remove element 0, the array gets shifted down by 1 and your other elements are in the wrong positions. One way to solve this would be to sort your input els array in descending order so it will pop element 3, then 1, then 0.

els.sort(function(a, b){return b-a});

els.each(function(key, val) {
        console.log(key);
        req-fields.splice(key,1);
    });

Variation on Richard Hamilton's. Note that both of ours will return a new array, not actually modify the original array object.

function removeIndexes(array, indexes) {
    return array.filter(function(element, i) {
        return indexes.indexOf(i) === -1;
    });
}

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