Home > OS >  How to store the removed items into new array after splice?
How to store the removed items into new array after splice?

Time:10-18

So, basically I'm trying to remove the item from an array of objects by index using splice, and it's working fine, but I would like also to store the removed collection into new Array, and sadly I'm only getting one element after clicking, and it's not giving me a collection;

const toArchive = (arr, index) => {
    arr.filter((elem, i) => {
        if (i === index) {
            return elem;
        }
    })
    let shallowCopy = [];
    shallowCopy.push(...arr.splice(index, 1));
    listToView(arr);
    console.log(shallowCopy);
}

This is what I'm getting:

[{…}]
[{…}]
[{…}]
[{…}]

The desired result:

(4) [{…}, {…}, {…}, {…}]

part of main code: http://jsfiddle.net/k8qa3cyp/1/

CodePudding user response:

You will want to move the shallowCopy variable declaration outside of your function.

And console.log after the function was invoked.

  • Related