3

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.

2
  • javascript doesn't have associative arrays, they are object literals and have no order. If using jQuery look at $.extend() Commented Sep 14, 2016 at 14:02
  • "If I want to clone an array, I can use the slice() function" No you can not. Commented Sep 14, 2016 at 14:29

3 Answers 3

3

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]);
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.