Splice doesn't copy array of objects [duplicate] - javascript

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.

Related

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)

How to remove an object from an array without returning a new array while using native javascript [duplicate]

This question already has answers here:
remove objects from array by object property
(15 answers)
Closed 6 years ago.
I have an array of objects such as Id:1, Name:Greg
Now I need to remove the object with an Id of 5.
I just need the existing array with the item removed, not a new array.
I don't want to use an external library to do this.
(The suggested duplicate answer is for deleting a number of objects at once, which is not what I want to do.)
What I would like to do is call
remove(theArray, theObject);
and it would remove it from the array.
Look into array.splice method. You can pass it the index if object and 1 for delete count. This modifies the original array.
The splice() method changes the content of an array by removing
existing elements and/or adding new elements.
array.splice(start, deleteCount[, item1[, item2[, ...]]])
var index = items.indexOf(itemToFind);
items.splice(index, 1);

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>

Iterating over sparse arrays [duplicate]

This question already has answers here:
How should I iterate over a sparse array in index order?
(2 answers)
Closed 6 years ago.
This answer says that the best way to iterate over sparse arrays is to use for X in Array
However, when I tried this I tripped up because the type of X was a string, rather than the integer index I was expecting. (All fine until I added it to another integer...)
var arr = [];
arr[10000] = "Hello";
var shifted = []
for (var x in arr)
shifted[10+x] = arr[x];
"Expected":
shifted[10010] = "Hello
Actual
shifted["1010000"] = "Hello"
Is there a better way of iterating a sparse array using the index, or should I just use Number(X) where required?
This is how V8 (and others JavaScript engines) handles arrays:
V8 uses two different methods to handle arrays:
Fast elements:
Designed for arrays where set of keys are very compact. They have a linear storage buffer that can be accessed very efficiently.
Dictionary elements:
Designed for sparse arrays which don’t have every elements inside of them. It is actually a hash table, more expensive to access than “Fast Elements”
Source: http://thibaultlaurens.github.io/javascript/2013/04/29/how-the-v8-engine-works/
When you are using a sparse array, the key is converted to string and then hashed. If you want numeric keys: don't use a sparse array or manually convert the key to a number.

copying an array of objects in javascript [duplicate]

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

Categories