This question already has answers here:
Why does Array.prototype.push return the new length instead of something more useful?
(6 answers)
Closed 4 months ago.
If I do
var a = [].push(undefined);
console.log(a);
it gives output as 1 even though undefined was pushed to the array. Any idea why?
You're testing it the wrong way. a is not defined as the array, as I think you suppose it to be. Try this:
var a = []
a.push(undefined);
console.log(a);
You are assigning the return value of push function to variable a. push returns the length of the array after pushing the current element in context. So, it returns 1 after pushing undefined in the array.
its pushing the length of array inside not the elements
example
var a = [].push(5,6,7,8);
console.log(a); //gives 4
Push returns the new length of the array, and thats what is stored in a
There was no explicit check has been done when assigning a new property to array object. Assigning a new property in the sense, setting 0,1,2..n properties with values, based on the length of the array.
Repeat, while items is not empty
Remove the first element from items and let E be the value of the element.
Let setStatus be Set(O, ToString(len), E, true).
ReturnIfAbrupt(setStatus).
Let len be len+1.
You can see it here. Step 8.
Related
This question already has answers here:
Js remove element from array without change the original
(4 answers)
Closed 13 days ago.
If I have an array a = [1,2,3,4] and I want to return it with the 3 removed, there are two ways I can do it:
let b = [...a] // or a.slice()
b.splice(2,1)
return b
or
return [...a.slice(0,2), ...a.slice(3,4)]
Advantage of the second is that it's one line. Disadvantage is that it's verbose. I thought of writing a helper function that contains the logic of the first approach, so that I'd be able to call it in one line elsewhere.
Is there an alternative? Something like splice but that returns that spliced array rather than mutating it and returning the spliced-out elements.
Since you know the indicies you want to remove, you can use the Array.prototype.filter method.
const a = [1,2,3,4];
const b = a.filter((_, i) => i !== 2);
console.log(b);
If you need to remove a range, you can just do something like 2 < i || i > 3.
.filter makes a copy of the array, copying the values where the callback function evaluates truthy and ignores the values where the callback function evaluates falsy.
This question already has answers here:
Copy array by value
(39 answers)
Closed 12 days ago.
I need to be able to record a previously existing variable in an array, and it should remain unchanged after the fact. The current problem is that whenever I set the variable to the value of another variable, it "follows" the value of the "reference variable". How can I prevent this from happening?
I have tried:
Pushing an empty new variable and setting it's value a line later to the variable that needs to be stored.
Pushing the variable as is into the array.
Using constants. This just froze the array and made me unable to record anything on it...
Sample code:
class dummy {
constructor (val1, val2) {
this.val1 = val1
this.val2 = val2
}
}
let data = []
let dummy1 = new dummy(1, 2)
data.push(new dummy(dummy1.val1, dummy1.val2)) // Keep in my that I have tried other ways of doing this.
dummy1.val1 = 3
dummy1.val2 = 4
console.log(dummy1)
console.log(data[0])
Desired output:
3, 4
1, 2
Current output:
3, 4
3, 4
Please, no alternatives to using an array.
Not sure if this would help,
You can make a variable immutable after changing it by using Object.freeze(). Object.freeze() is a method that prevents further changes to an object by making it read-only and non-configurable.
If your "var" is a object with plain properties, use this for pushing:
data.push({ ...dummy1 })
If not -contains other objects for example- then you need a deep copy as the others already said.
This question already has answers here:
Copy array by value
(39 answers)
Closed 2 years ago.
q = [3,2,4,1]
let copyQ = q;
copyQ.sort();
console.log(q) // 1,2,3,4 --------> This doesnt make sense.
console.log(copyQ) //1,2,3,4 -----> This makes sense
I had expected that q would remain the same, i.e unsorted as in line 1, because we had sorted copyQ, but it is not the case.
Whats going on there?
sort() function mutates initial array. As soon as your array is copied by link - it is expected. Use spread operator to avoid mutation of initial array. Spread operator will create a copy of your array that will be separate from initial one:
q = [3,2,4,1]
let copyQ = [...q];
copyQ.sort();
console.log(q)
console.log(copyQ)
This question already has answers here:
Array.fill(Array) creates copies by references not by value [duplicate]
(3 answers)
Closed 6 years ago.
I have found that these two different methods of creating an array of arrays produce different behaviors:
// Method 1
for (var arr1 = []; arr.push([]) < len;) {}
// Method 2
var arr2 = new Array(len).fill([])
The arrays created look the same in the console, however they behave differently in my code. What could be causing this?
The difference is that in the 1st method each index points to a different array, while in the Array#fill all indexes point to the same array.
Note: the 1st method will not create an array of arrays
var len = 3;
var arr1 = [];
// Method 1
for (var arr1 = []; arr1.push([]) < len;) {} // new sub array is pushed into arr1
// Method 2
var arr2 = new Array(len).fill([]) // each place in the array is filled with a reference to the same array
arr1[0].push(1); // push to the 1st element of arr1
arr2[0].push(1); // push to the 1st element of arr2
console.log('arr1: ', JSON.stringify(arr1)); // only the 1st sub array contains 1
console.log('arr2: ', JSON.stringify(arr2)); // all sub arrays contain 1
Update: While the answer below is technically accurate, and is another difference between the two methods, #Ori Drori's answer is almost certainly what the OP is looking for.
I'll take a stab at this, but more context would be helpful.
In common practice, these two statements typically behave the same, but there is a key difference - when you use the new keyword, the Javascript interpreter calls the Array constructor.
If you were to overwrite the Array constructor, this would only apply to arr2 which was defined with the new keyword. arr1 created with the array literal would still be a Javascript array.
As an example, let's say I wrote the following code:
function Array() {
}
Method 1 would still work, but Method 2 would return a TypeError indicating that fill is not a function.
Interestingly, using the Array literal (Method 1) still calls the Array constructor, so if I did a console.log("test"); within the Array construction this would still be printed to the console when using either method. BUT, when the Array literal (Method 1) is used, the object itself still remains a standard Javascript array even if the Array constructor is overwritten.
This question already has answers here:
What is the most efficient way to deep clone an object in JavaScript?
(67 answers)
Closed 8 years ago.
I created an object array with some values. Then I created another object array and initialized it with the first one. Then I pushed a value in 2nd array, and console logged both arrays. Both arrays had same value. Why is this happening and how can we stop this?
My Code:
var a = { "filters": [] }; // 1st object array
var keyValue = {};
// pushed 2 values in "a" array
keyValue["abc"] = "123";
a.filters.push(keyValue);
keyValue["def"] = "456";
a.filters.push(keyValue);
var b = a; // created another object array & initialized it with "a" array
var keyValue1 = {};
// pushed 1 value in "b" array
keyValue1["ghi"] = "789";
b.filters.push(keyValue1);
console.log(a);
console.log(b);
This prints same values for a and b.
How do I push values into 2nd array without updating 1st one?
Assignment such as var b = a for a object creates an object 'b' which references(just like pointer) the same location pointed by 'a', in general. You may find this link helpful.
However you can create/clone a new array with slice method. var b = a.slice()
You can use
var b = JSON.parse(JSON.stringify(a));
https://stackoverflow.com/a/4591639/1623259
Both are pointing to the same values in the memory when you say:
var b = a;
So if you change a, b will be affected and vice versa, you need to copy using a loop.
EDIT
use this line of code which I get from this post
var b= a.slice(0);