user3503550
user3503550

Reputation: 83

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.

Upvotes: 3

Views: 1143

Answers (3)

Redu
Redu

Reputation: 26191

Cloning an array properly (without leaving any references in the nested structure) is not that simple. You need a tool for that. Unfortunately it is not a part of standard array methods. You have to develop it yourself. Such as

Array.prototype.clone = function(){
  return this.map(e => Array.isArray(e) ? e.clone() : e);
};

Once you have this tool at hand you can clone the array first and then assign whatever item of the clone array you wish; such as array1[i] = array2.clone()[i];

Upvotes: 0

Mort Rainey
Mort Rainey

Reputation: 43

You can do this:

array1[i] = Object.assign({}, array2[i]);

But it doesn't work if there are primitives an array. Also you can use slice method like you wrote:

array1[i] = array2.slice(i, 1);

Upvotes: 0

taguenizy
taguenizy

Reputation: 2265

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]);

Upvotes: 3

Related Questions