JavaScript: 5 ways to create a new array from an old array

Updated: February 19, 2023 By: Khue 2 comments

There are multiple ways to create a true new array from an old array in modern Javascript (ES6 or beyond).

Using the spread syntax (shallow copy)

This method works perfectly when you try to clone a one-level (or one-dimensional) array. Thankfully, one-level arrays are much more popular than multi-level arrays.

Example of how the spread syntax works with a one-level array:

const arrOld = [1, 2, 3, 4, 5]
const arrNew = [...arrOld]
console.log(arrNew)

Output:

[ 1, 2, 3, 4, 5 ]

This example proves that the method doesn’t work with multi-level arrays (such as an array of objects or an array of arrays):

const oldArray = [
    { name: "Tom", age: 28 },
    { name: "John", age: 32 },
]

const newArray = [...oldArray]
newArray[0].name = 'John new'

console.log('New array: ', newArray)
console.log('Old array: ', oldArray)

The output will look like this:

New array:  [ { name: 'John new', age: 28 }, { name: 'John', age: 32 } ]
Old array:  [ { name: 'John new', age: 28 }, { name: 'John', age: 32 } ]

When you change the new array, the original array changes too. The reason is while the first level is copied, the deeper levels are only referenced.

Using JSON: The perfect method for any scenario (deep copy)

This method isn’t concise, but it works perfectly with both one-level and multi-level arrays.

Example:

const oldArray = [
  { name: 'Tom', age: 28 },
  { name: 'John', age: 32 },
];

const json = JSON.stringify(oldArray);
const newArray = JSON.parse(json);

newArray[0].name = 'John new';
console.log('New array: ', newArray);
console.log('Old array: ', oldArray);

Output:

New array:  [ { name: 'John new', age: 28 }, { name: 'John', age: 32 } ]
Old array:  [ { name: 'Tom', age: 28 }, { name: 'John', age: 32 } ]

When the new array is manipulated, the original array is not affected.

Using slice() (shallow copy)

This method is equivalent to the first method in this article.

The code:

const arrOld = [1, 2, 3, 4, 5]
const arrNew = arrOld.slice()
console.log('new array: ', arrNew)

Output:

new array:  [ 1, 2, 3, 4, 5 ]

Using from() (shallow copy)

This method is equivalent to the first and the third methods.

The code:

const arrOld = [1, 2, 3, 4, 5]
const arrNew = Array.from(arrOld)
console.log('new array: ', arrNew)

Output:

new array:  [ 1, 2, 3, 4, 5 ]

Using concat() (shallow copy)

This method is equivalent to the first, third, and fourth methods.

The code:

const arrOld = [1, 2, 3, 4, 5]
const arrNew = [].concat(arrOld)
console.log('new array: ', arrNew)

Output:

new array:  [ 1, 2, 3, 4, 5 ]

That’s it. Happy coding and have fun with Javascript! In case you have questions, just let us know by leaving a comment.

2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments