Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I copy the value of a single element from a JavaScript array into another array at the same position?

If I want to clone an array, I can use the slice() function, but what if I want to "clone" a single element? I want to do something like this:

array1[i] = array2[i];

but I want to copy the value, not the reference. How can I do this? Also, will the solution work for associative arrays too? For example:

array1["one"] = array2["one"];

Thank you in advance.

like image 770
user3503550 Avatar asked Feb 01 '26 18:02

user3503550


1 Answers

You could use Object.assign and Array.splice

   var cloneItem = Object.assign({}, array1[i]);
   array2.splice(i, 0, cloneItem);

EDIT
The previous adds a clone item in the position, pushing the rest of the elements to the right. If you simply want to replace just do

array2[i] = Object.assign({}, array1[i]);
like image 187
taguenizy Avatar answered Feb 04 '26 07:02

taguenizy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!