开发者

.splice() array with array of non-sequential indexes - javascript

开发者 https://www.devze.com 2023-02-15 03:38 出处:网络
I have an array like this Array[\'one\',\'two\',\'three\',\'four\',\'five\'] and I have an array like this

I have an array like this

Array['one','two','three','four','five']

and I have an array like this

Array['2','4','0']

indicating the indexes of the elements in the first array I wish to remove or .splice() so the resulting array would look like this

Array['two','four']  // <--- note no undefined positions

If you try and loop through the indexes and just do a splice for each one, after the first splice your indexes change according to the element that was removed.

How can I accomplish t开发者_StackOverflowhis?


You can start splicing the indexes from the array in reverse order. i.e. Loop from the length of array to 0.

First splice index 4 and then index 2.

EDIT: As you mentioned the indexes array need not be in same order, you can sort the indexes array in ascending order and then implement the above logic.

0

精彩评论

暂无评论...
验证码 换一张
取 消