0

I have the following code:

var cards = [
    {
        name: 'John',
        age: 26
    },
    {
        name: 'Marc',
        age: 27
    },
    {
        name: 'Nathan',
        age: 21
    }
];
var save = cards;
for(var i = 0;i < cards.length; i++){
    if(i == 0){
        cards.splice(i,1);
    }
}
cards = save;

And at the end cards and save are the same, Marc and Nathan. And I want my cards be the array it was before, but I can't understand why it is not.

Here is a jsfiddle: https://jsfiddle.net/6g8bkauo/

2 Answers 2

2
var save = cards.slice()

NB. the card references, the objects in each array, will still be shared.

Sign up to request clarification or add additional context in comments.

Comments

0

Your referencing the array, you have to make a copy, just do it like this using lodash

var save = _.cloneDeep(cards);

Or without a library:

var save = JSON.parse(JSON.stringify(cards));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.