Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing item from array and add it to another array

I am displaying to the user a series of divs with content in them and the user is able to remove the div from the page so that they no longer see it.

I would like to take the same div content that was removed from an array and add it into another array that will be used to populate a dropdown list.

this is what i have:

//Remove function
removeCategory(index: number): void {
    this.categories.splice(index, 1);
}
//Array
categories: Array<Item> = [
    new Item(1, 'test1'),
    new Item(2, 'test2')
];
//New Array to add previous removed item
ddoptions: Array<object> = [];

Is it possible to do a push statement before the splice in the removeCategory function? I am not sure of what to pass in since doing this gives me an error:

this.ddoptions.push(index);
like image 637
bluePearl Avatar asked Sep 19 '25 04:09

bluePearl


1 Answers

Updated for 2020

With the newer ES specifications you can also use the destructuring assignment operator on an array, which means you don't have to use concat or apply a push function in a given context. This was actually around at the time I wrote this originally, but it's far more common to see now.

this.ddoptions.push(...this.categories.splice(index, 1));

However the rules from below still apply, using push and splice will mutate existing arrays, so concat should probably still be used if you want immutability.


Original Answer

You can splice into the push method directly, as splice returns the removed object.

this.ddoptions.push(this.categories.splice(index, 1)[0]);

The splice method actually returns an array of elements that were removed. In your case, you are only removing one so the above code works. If you are removing one or more elements, you can add these to the second array with several methods.

By using concat to generate a new array:

this.ddoptions = this.ddoptions.concat(this.categories.splice(index, 1));

This may break things because ddoptions is no longer the same object. It depends on what you're doing and what angular is doing.

You can pass the array as multiple arguments to push by applying the push prototype.

[].push.apply(this.ddoptions, this.categories.splice(index, 1));

In this way ddoptions will remain as the same array and will push all new elements into it.

like image 112
James Hay Avatar answered Sep 20 '25 17:09

James Hay