Hack-R Hack-R - 2 months ago 11
Javascript Question

Add item to a 2nd list by index of item in the 1st list

I have 2 lists.

I have an Angular service with a

splice
-based method that allows me to remove items from the first list (called "
items
") based on their index via a
ng-click
action.

service.removeItem = function (itemIndex) {
items.splice(itemIndex, 1);
};


What I would like to do is to add the removed item to the 2nd list (called "
bought
"), using the same index that is passed to
slice
.

I thought perhaps I could put this functionality into the same function (
removeItem
) like this:

service.removeItem = function (itemIndex) {
bought.push(itemIndex);
items.splice(itemIndex, 1);
};


However, that does not seem to work. I tried a few variations (like
bought.push(items.itemIndex)
) unsucessfully.

Answer

Use splice to insert the element to be removed at the same index in the second array.

service.removeItem = function (itemIndex) {
    var currItem = items[itemIndex];
    // Insert the element to be removed
    // at the same index in the other array
    bought.splice(itemIndex, 0, currItem);
    items.splice(itemIndex, 1);
  };

or instead of accessing the element before hand, use the one returned when the element is removed.

service.removeItem = function (itemIndex) {
    var currItem = items.splice(itemIndex, 1);
    bought.splice(itemIndex, 0, currItem);
};