简体   繁体   中英

Concise way to copy array elements in JavaScript

I need to copy elements from one JavaScript array to another. Yes, I know there are oodles of questions regarding cloning an array, but most of the related answers create a new copy of the existing array. I already have a copy of an array I want to keep. I merely want to update the values with those of another array. Like this:

//I already have this array
const oldArray = new Array(10);
//here is a new array I get from somewhere
const newArray = new Array(10).fill(3);
//I just want to copy the values, not create a new array
for(let i = 0; i < newArray.length; i++) {
  oldArray[i] = newArray[i];
}

Is there some cool, slick way to do that, perhaps using ES6 syntax?

You can use Array#splice to remove from the start an amount of items in the oldArray equals to the newArray length, and then add to it all items in the newArray :

 const oldArray = new Array(10).fill(4); const newArray = new Array(5).fill(3); oldArray.splice(0, newArray.length, ...newArray); console.log(oldArray); 

You can use Object.assign()

 const arr = [1,2,3]; const values = [4,5,6]; Object.assign(arr, ...values.map((prop, index) => ({[index]:prop}))); console.log(arr); 

You could just use Object.assign with an array as target and an array as source.

All values of own enumerable keys of the array, are transfered to the target array with the same index.

 var oldArray = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], newArray = [10, 11, 12, 13, 14]; Object.assign(oldArray, newArray); console.log(oldArray); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM