0

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 this?

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

+1 for being clever, but there is no guarantee the "indexes" array will be in a given ordering. I'll update the question to make that clear.
@jondavidjohn - No issues. Just sort the indexes array to make it in ascending order. Updated my answer too. Hope this helps :)

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.