bluePearl bluePearl -4 years ago 127
Javascript Question

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);
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:


Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download