copying an array of objects in javascript [duplicate] - javascript

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Copying array by value in javascript
How to copy an array of objects to another array in Javascript?
var qwerty1 = arr;
var qwerty2 = arr;
Both qwerty1 and qwerty2 may look different but point to the same reference.
I read somewhere that "assigning a boolean or string to a variable makes a copy of that value, while assigning an array or an object to a variable makes a reference to the value." So my two arrays post different operations return the same objects.
Any light in this regard?

The idiomatic way to copy an array in Javascript is to use concat:
var qwerty1 = arr.concat();
var qwerty2 = arr.concat();

Related

How to merge two arrays at run time [duplicate]

This question already has answers here:
Why Doesn't Array Concatenation Work in Javascript? [closed]
(3 answers)
Closed 2 years ago.
I am getting below like values at runtime. Below is for only example. I will have same array structure at runtime. I want to merge them.
let finalSearchResult =[];
data [{"a":1000,"a":1000001,"a":10000002,"D":5000000}]
data [{"P":1000,"Q":1000001,"R":10000002,"S":5000000}]
finalSearchResult.concat(finalSearchResult,data);
but its not working. When I am printing finalSearchResult its coming as null.
The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.
please refer to:
Array.prototype.concat documentation
Therefore:
finalSearchResult = finalSearchResult.concat(data);
Will be the correct way to concat the arrays.

Javascript associative array does not support Array.prototype.map function [duplicate]

This question already has answers here:
Length of a JavaScript associative array
(4 answers)
Closed 4 years ago.
After long times programming, I don't know why never have seen this:
var array = [];
array['one'] = 1;
console.log(array.length);
Here is a fiddle that shows array.length is zero (0):
https://jsfiddle.net/0c9v5txe/1/
Of-course, I don't need the length of array, just array.map is not working when the length is zero.
Isn't there really a way to force Javascript update the length of an associative array when adding a new item?
JavaScript doesn't have a feature called "associative arrays".
It has objects, and arrays are a type of object designed to hold numerically indexed values. (The length property on an array is calculated based on the highest numbered numerical property).
(Since arrays are a type of object, you can store arbitrary properties on them, but this is not a good practice).
If you want to store named properties, then do not use an array. Use a plain object or a Map. These serve the same purposes as associative arrays in other languages.
You can count the enumerated properties of an object by extracting them into an array and then checking its length.
var myObject = {};
myObject.one = 1;
console.log(Object.keys(myObject).length);
you need to pass index, not value
array[index] = value;
var array = [];
array[0] = "one";
console.log(array.length)

Splice doesn't copy array of objects [duplicate]

This question already has answers here:
How do you clone an array of objects in JavaScript?
(40 answers)
using splice(0) to duplicate arrays
(3 answers)
Closed 6 years ago.
In this plunk I have an example of an array of objects a that I copy with slice() to b. I alter one of the objects in a but it changes also b. Isn't slice supposed to copy the array, including its contents? I need a and b to have different pointers.
Javascript
var a = [{x1:1, x2:2}, {x1:3, x2:4}];
var b = a.slice();
a[1].x1 = 5;
console.log(b[1]);
this prints:
x1: 5
x2: 4
From MDN:
For object references (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.
For strings, numbers and
booleans (not String, Number and Boolean objects), slice copies the
values into the new array. Changes to the string, number or boolean in
one array does not affect the other array.
Performing a deep copy on objects in the array is difficult, but this answer suggests a way to do it, as long as your array only contains JSON-serializable content:
var clonedArray = JSON.parse(JSON.stringify(originalArray));
You can try to do Deep copy with jQuery:
var b = $.extend(true,{},a);
This does a proper deep copy of all your variables.

Javascript array alllocation [duplicate]

This question already has answers here:
Are Javascript arrays sparse?
(7 answers)
Closed 6 years ago.
I was dealing with a problem and got to the point where I thought I could use the Ids to my entity instances as array indices for easy lookup.
var myArray = [];
myArray[obj.Id] = true;
Assume obj.Id is 1000 here, so will be myArray.length. Am I allocating 1000 bytes for a single boolean value here or is it just returning the maximum index as length?
It won't be allocating so many bytes.
But what you are really looking for is an key-value object like
var myObj = {};
myObj[obj.Id] = true;
//then to access
console.log(myObj[obj.Id])

Assigning objects in Javascript: shallow or deep copy? [duplicate]

This question already has answers here:
JavaScript by reference vs. by value [duplicate]
(4 answers)
Closed 7 years ago.
I want to know if javascript does shallow or deep copy when copying objects.
const a = ['value1', 'value2'];
const b = ['value3', 'value4'];
const new_ab = [a, b];
new_ab are going to have new allocated values or a reference? If it is a deep copy, how can I make it to be swallow? Thanks.
As alluded in the comments, JavaScript operates entirely on references, the only exception being that primitive values are kept on the stack and a program does not therefore require a reference to access them. In your example all variable declarations create new values - each an instance of Array - however what is returned from declaring an array is a reference, not the array itself. For example, [1, 2] is an array of values (integers), but [a, b] is an array of references.
So... nothing is copied. We can demonstrate this by placing an object as an element of an array and inspecting that a previously assigned property is still accessible through the new 'parent' array.
(And to answer your question in the comments, yes, your example is more performant than if you (or JavaScript) were to copy values.)
'use strict';
const arrayOne = [];
arrayOne.someProperty = "This string is a property of `arrayOne`, " +
"accessed via the reference to it in `arrayTwo`."
const arrayTwo = [arrayOne];
span.innerHTML = arrayTwo[0].someProperty;
<span id="span"></span>

Categories