views:

289

answers:

1

If I have an array

private var temp:Array = [item1, item2, item3, item4, item5, item6, item7...etc];

and two variables for items in the array:

private var firstPosition;

private var secondPosition;

Is there a way to remove BOTH items at once?

Say, if firstPosition = item4, and secondPosition = item7...then firstPosition = temp[3] and secondPosition = temp[6]

But if I write:

temp.splice(firstPosition, 1);

Then secondPosition is them temp[5] instead of temp[6]...since one has been removed from the array.

I have been writing:

temp.splice(firstPosition,1);
temp.splice(secondPosition-1,1);

I don't think this is right...especially if secondPosition is at the beginning of the the "temp" array (i.e. temp[0]).

Is there a way to remove two items at once from an array, if they are not side-by-side??

A: 

Start removing from position with maximum index:

// it will not change firstPosition if firstPosition < secondPosition
temp.splice(secondPosition, 1); 
temp.splice(firstPosition, 1);

This will not affect positions with lower index.

Ivan Nevostruev
How do I sort the two variables, firstPosition and secondPosition? Using indexOf?
redconservatory
You can't sort variables. Just compare them to make sure that `firstPosition < secondPosition`. For example `if (firstPosition > secondPosition) swap_values_of(firstPosition, secondPosition)`
Ivan Nevostruev