Looking for a resource to explain why when I run the below code, my original array doesn't change.
arr = [1,2,3,4];
for(let val of arr){
val = val * 2;
console.log(val);
}
console.log(arr);
I am learning about for...in and for...of loops and not sure why my console.log(arr) doesn't print out [2,4,6,8].
The problem here is that the the identifier val is being overwritten. With another integer and val is just a temp variable invoked each iteration of the loop. If you used an object, and did not reassign the variable, your values would remain intact
// Object values
var x = [{z:1},{z:2}]
for(let y of x){
// No reassignment
y.z=3;
}
console.log(x); //[{"z":3},{"z":3}]
If you want to modify an array of simple types in place, you can do something like:
var q = [5,6,7];
for( i in q){
q[i] = q[i] * 2;
}
console.log(q); //[10, 12, 14]
Use a for loop, which enables you to make the assignments "stick" in the original array.
arr = [1,2,3,4];
for (var i=0; i < arr.length; i++) {
arr[i] = 2*arr[i];
console.log(arr[i]);
}
The issue with what you were originally doing is that val is just a variable with no real connection to the underlying array. Hence, doubling val has no effect on the array itself.
You are modifying and not inserting in back.
Better you use for each this case. So that you'll be able to modify the array. Using of make things complicated.
arr = [1,2,3,4];
arr.forEach(function(part, index, array) {
array[index] = array[index]*2;
});
console.log(arr);
You can achieve this using forEach too, which runs a particular function for every value in the array.
arr = [1,2,3,4];
arr.forEach((d, i, arr) => arr[i]*=2);
console.log(arr);
Related
I have an array that contains elements my goal is to slice some of the elements inside the array, then later I want to reassign the original array with a new array which is a sublist of the original array but it seems like I can't make that happen please help.
let arr = [1,2,3,4,5]
function subList(arr){
for(let i = 0; i < arr.length; i++){
let res = arr.slice(0,i)
if(i === 3){
arr = res;
}
}
}
subList(arr)
console.log(arr)
// expected output [1,2,3]
There are a lot of ways to do it.
Why it isn't working for you:
You are passing the arr into the variable and since it is an object ideally any change you make to it should be reflected outside. But you aren't actually mutating/changing anything in your passed argument, you are reassigning it (with arr=res). So that will not make any change to the arr outside.
If you do something like .push(),.pop(), which are operations on the array without reassigning it, that should actually change it.
Example modifying your code with operations that actually modify the array instead of replacing it splice() , push:
let arr = [1,2,3,4,5]
function subList(arr){
for(let i = 0; i < arr.length; i++){
let res = arr.slice(0,i)
if(i === 3){
arr.splice(0,arr.length);
arr.push(...res);
break;
}
}
}
subList(arr)
console.log(arr)
Pass in an index to the function and just return arr.slice(0, i);.
let arr = [1, 2, 3, 4, 5]
function subList(arr, i) {
return arr.slice(0, i);
}
console.log(subList(arr, 3));
let list = [1,2,3,4,5]
function subList(arr,n){
for(let i = 0; i < arr.length; i++){
if(i === 3){
let res = arr.slice(0,i)
list = res;
}
}
}
subList(list,0)
console.log(list)
Problem statement :
Clean the room function:
Input
[1,2,4,591,392,391,2,5,10,2,1,1,1,20,20],
make a function that organizes these into individual array that is ordered.
For example answer(ArrayFromAbove) should return:
[[1,1,1,1],[2,2,2], 4,5,10,[20,20], 391, 392,591].
My Code:
const arrNum = [1,2,4,591,392,391,2,5,10,2,1,1,1,20,20] ;
function org(arr) {
let finalarr = [];
let arrnew = [];
let val = 0;
arr.sort((function(a, b){return a-b}));
//console.log(arr);
for (i=0; i<arr.length; i++){
if (arr[i] != 0) {
val = arr[i];
arrnew.length = 0;
arrnew.push(arr[i]);
arr[i] = 0;
for (j=0; j<arr.length; j++){
if (arr[j] == val && arr[j] != 0) {
arrnew.push(arr[j]);
arr[j] = 0;
}
}
finalarr.push(arrnew);
console.log(arrnew);
}
}
return finalarr;
console.log(finalarr)
}
org(arrNum)
But this doesn't seem to give desired answer :
Not sure what I am doing wrong. I have found the other solutions but I need to know what is wrong in my code please.
Objects and arrays are pushed as a pointer to the original object . Built-in primitive types like numbers or booleans are pushed as a copy.
In your code your are pushing arrnew in finalarr
finalarr.push(arrnew);
Which means reference of arrnew is pushed in finalarr.
So after first iteration of for loop:
finalarr = [[1,1,1,1]]
arrnew = [1,1,1,1]
Here element of array finalarr is acutally pointer to array arrnew.
So, In the second iteration the statement
arrnew.length = 0
Will empty the array arrnew, as array finalarr have pointer to array it also gets modified:
finalarr= [[]]
Then inner for loop will push three 2 in array arrnew = [2,2,2], so finalarr become [[2,2,2]].
At the end of second iteration finalarr.push(arrnew); will push one new reference of arrnew in finalarr. So finalarr will become
finalarr = [[2,2,2], [2,2,2]]
So at the end of all iterations, finalarr will have 9 pointers, all pointing to arrnew and the final value in arrnew is [591].
finalarr = [[591],[591],[591],[591],[591],[591],[591],[591],[591]]
You can update you code, just replace arrnew.length = 0 with arrnew = []
This question already has answers here:
Copy array by value
(39 answers)
Closed 4 years ago.
I was trying to multiply each of the values in an array by 2 and push the value to another array at each loop. I have no idea why the following code seems to triger an infinite loop which crashes the browser. I have other solutions to get the same result but I just wanted to know the root cause behind the crash so please educate me. Thanks!
multipliedBy([1,2,3], 2) //expected result: [1,2,3,2,4,6]
function multipliedBy(arr, num){
var oldArr = arr;
for(var i=0;i<arr.length;i++){
oldArr.push(arr[i] * num);
}
return oldArr;
}
Try like this way with cloning the array instead of referring the same array while using push(),
console.log(multipliedBy([1,2,3], 2)) //expected result: [1,2,3,2,4,6]
function multipliedBy(arr, num){
var oldArr = [...arr]; //clone using spread
for(var i=0;i<arr.length;i++){
oldArr.push(arr[i] * num);
}
return oldArr;
}
Useful note from comment: Because oldArr and arr point on the same array, hence arr.length changes with every .push() - Andreas
When you do var oldArr = arr; it is a reference to arr. In the loop you are looking at the length arr.length and when you push to oldArr, you are pushing to arr and the length keeps increasing so you keep looping.
function multipliedBy(arr, num) {
var oldArr = arr.slice(0);
for (var i = 0; i < arr.length; i++) {
oldArr.push(arr[i] * num);
}
return oldArr;
}
console.log(multipliedBy([1, 2, 3], 2))
or if you do not want to clone the array, than just set it a variable before you alter it.
var oldArr = arr;
var len = arr.length;
for(var i=0; i<len; i++){
I am trying to push objects into an array inside a for loop. The expected data structure is
[{"valueItem":"item0"}, {"valueItem":"item1"}, {"valueItem":"item2"}, {"valueItem":"item3"}, {"valueItem":"item4"}]
The code I have is
var arr = [];
var obj = {};
for(var i = 0; i < 5; i++){
arr.push(obj.valueItem = 'item'+i);
}
console.log(arr)
But the what I get back is
["item0", "item1", "item2", "item3", "item4"]
What am I doing wrong?
try:arr.push({"valueItem":"item"+i});
Ok, to clarify, you have to push an object in your array to get your expected array.
push(obj.valueItem = 'item'+i) works sortof because you are assigning inside push.
The below works ;)
var arr = [];
for(var i = 0; i < 5; i++){
var obj = {};
obj.valueItem = 'item' + i;
arr.push(obj);
}
console.log(arr)
By doing this arr.push(obj.valueItem = 'item'+i);
you are not pushing obj into the array, you are making an assignment
obj.valueItem = 'item'+i
the result of an assignment is the returned value, in this case it is item+i,
to push objects into an array do this
arr.push({
valueItem: "item0"
})
First define object, then push it to array:
var arr = [];
for(var i = 0; i < 5; i++){
arr.push({valueItem: 'item'+i});
}
console.log(arr)
Based on your try:
var arr = [];
for(var i = 0; i < 5; i++){
var obj = {};
obj.valueItem = 'item'+i
arr.push(obj);
}
console.log(arr)
Looks like you're not actually creating a new object for each loop. Maybe try:
arr.push( { valueItem: 'item'+i } );.
The {} will create a new hash object, which we would push onto the array.
In your inital code you only made one object, so the thing you were pushing was the return value of obj.valueItem='item'+i. Since the return value of a string assignment would be the actual string, you were just creating an array of strings.
Your expected result has a different object for each element. Even though they are are similar in that they have a valueItem proprerty, they are all different. So you need to create a new one on each loop iteration. You need
arr.push({valueItem:"item"+i});
which creates a new one each time.
I have an array and I want to overwrite all values in it (that are all numbers) with a 0. So the array already exists.
I can do this with a for loop. However, is there a fill() call of some kind like the Java Arrays.fill()?
A very simple for-loop is all you need. There's no fill-function in JavaScript.
var length = arr.length,
for (var i = 0; i < length; i++) {
arr[i] = 0;
}
You can use map for this.
var arr = [1,2,3];
arr = arr.map(function() {return 0});
//arr = [0, 0, 0]
The performance may be worse than a plain for loop.