Ambrosius Topor

Notiz — 2018-01-30

In Place Array Replacement

Because there is no chance of not losing track of a replaced object, a complete replacement has to be done differently.

var accounts = [/* values */]

Empty and Refill the Array

accounts.splice(0, accounts.length);
data.accounts.forEach(account => {
    accounts.push(account);
});

Extract to a generic function:

function replaceArray(array, newArray) {
    array.splice(0, array.length);
    newArray.forEach(item => {
        array.push(item);
    });
}
replaceArray(accounts, data.accounts)

Using the Spread Syntax

It can be simplified by using the spread syntax:

accounts.splice(0, accounts.length, ...data.accounts);

Comments

There are no comments yet.

Thanks for your contribution!
Your comment will be visible once it has been approved.

An error occured—please try again.

Add Comment