Skip to content
Fix Code Error

Copy array by value

March 13, 2021 by Code Error
Posted By: Anonymous

When copying an array in JavaScript to another array:

var arr1 = ['a','b','c'];
var arr2 = arr1;
arr2.push('d');  //Now, arr1 = ['a','b','c','d']

I realized that arr2 refers to the same array as arr1, rather than a new, independent array. How can I copy the array to get two independent arrays?

Solution

Use this:

let oldArray = [1, 2, 3, 4, 5];

let newArray = oldArray.slice();

console.log({newArray});

Basically, the slice() operation clones the array and returns a reference to a new array.

Also note that:

For references, strings and numbers (and not the actual object), slice() copies object references into the new array. Both the original and new array refer to the same object. If a referenced object changes, the changes are visible to both the new and original arrays.

Primitives such as strings and numbers are immutable, so changes to the string or number are impossible.

Answered By: Anonymous

Related Articles

  • Extract the different props between array of objects
  • Searching for matching elements between 2 arrays in C
  • How do I include certain conditions in SQL Count
  • Javascript sort array of objects based on another array
  • I have tried to implement mergesort and am unable to…
  • How do I copy a range of formula values and paste…
  • For-each over an array in JavaScript
  • Copy Paste Values only( xlPasteValues )
  • Form field border-radius is not working only on the…
  • Object is not updated (by Lambdas filter) when…
  • Creating a new Array from Normal Array and Array of objects
  • What does this symbol mean in JavaScript?
  • Creating a function that performs math on a given string
  • JavaScript - Compare 2 arrays and return which are…
  • What is the copy-and-swap idiom?
  • Copying an array of objects into another array in javascript
  • How to generate a random string of a fixed length in Go?
  • JavaScript gives NaN error on the page but variable…
  • How to retrieve the old and new values of a store state
  • How can I access and process nested objects, arrays or JSON?
  • Most efficient way to prepend a value to an array
  • How to add item to list in vue.js
  • How do SO_REUSEADDR and SO_REUSEPORT differ?
  • Open Weather Api (Show weather icon)
  • What is The Rule of Three?
  • In For each loop it edits both loops
  • How does PHP 'foreach' actually work?
  • Android - Find the index of ListView item by text
  • How can I add new array elements at the beginning of…
  • Copy array items into another array
  • What is a NullReferenceException, and how do I fix it?
  • How to stack every n rows of two numpy arrays
  • Are arrays in PHP copied as value or as reference to…
  • Logging best practices
  • data.table vs dplyr: can one do something well the…
  • Finding all possible combinations of numbers to…
  • Check element presence in array in another array
  • What are the undocumented features and limitations…
  • How can I replace values of Javascript Object with…
  • What is your most productive shortcut with Vim?
  • Backbone Collection.fetch gives me Uncaught…
  • Iterator invalidation rules
  • Why do I have to "git push --set-upstream origin "?
  • Reference - What does this regex mean?
  • What is the scope of variables in JavaScript?
  • Sorting 1 million 8-decimal-digit numbers with 1 MB of RAM
  • How can I manually compile a svelte component down…
  • Push method in React Hooks (useState)?
  • How can I find matching values in two arrays?
  • Smart way to truncate long strings
  • Programmatically Lighten or Darken a hex color (or…
  • python 3.2 UnicodeEncodeError: 'charmap' codec can't…
  • How do I correctly clone a JavaScript object?
  • What is a plain English explanation of "Big O" notation?
  • C compile error: Id returned 1 exit status
  • Polymer 2.x: dom-repeat does not observe changes to…
  • How to convert the following C++ code to C#
  • How to compare arrays in JavaScript?
  • Copy a variable's value into another
  • How do JavaScript closures work?
  • Adding multiple ranges to an array then using .value…
  • How to check two arrays of object has the same…
  • Vuex dynamic checkboxes binding
  • Push git commits & tags simultaneously
  • How to send push notification to web browser?
  • Getting the closest string match
  • How to prevent scrolling the whole page?
  • What are the nuances of scope prototypal /…
  • Fastest way to iterate over all the chars in a String
  • Property or method "key" is not defined on the…
  • How to insert data in only one type of Vector in…
  • Checkout another branch when there are uncommitted…
  • “tag already exists in the remote" error after…
  • Why and when to use angular.copy? (Deep Copy)
  • What is an IndexOutOfRangeException /…
  • Git - Pushing code to two remotes
  • How to Deep clone in javascript
  • How do I keep only the first map and when the game…
  • What does T&& (double ampersand) mean in C++11?
  • Why is my variable unaltered after I modify it…
  • How to know if two arrays have the same values
  • The definitive guide to form-based website authentication
  • Reference — What does this symbol mean in PHP?
  • How do I empty an array in JavaScript?
  • How to check identical array in most efficient way?
  • MSBuild doesn't copy references (DLL files) if using…
  • What is move semantics?
  • Dynamically allocating an array of objects
  • Mutating Arrays Vuex
  • Are arrays passed by value or passed by reference in Java?
  • How do I use arrays in C++?
  • Ukkonen's suffix tree algorithm in plain English
  • Easy interview question got harder: given numbers…
  • How do I merge two dictionaries in a single…
  • how to push array in javascript by turns?
  • What's the difference between struct and class in .NET?
  • Copy from one workbook and paste into another
  • How do you clear the SQL Server transaction log?
  • What's the best way of scraping data from a website?
  • Passing array to an array in numpy

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

Upgrading Node.js to latest version

Next Post:

Undo git pull, how to bring repos to old state

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error