Javascript 2-dimensional array: incrementing a specific item's value - javascript

I have a 2 dimensional array, with integers, and all what I want is to increment a particular item with a number.
The initial state:
var arr1=[];
var arr2=[1,2,3];
arr1.push(arr2);
arr1.push(arr2);
arr1.push(arr2);
arr1 now looks like this:
0:[1, 2, 3]
1:[1, 2, 3]
2:[1, 2, 3]
What I want is to increment the [0,0] element of this array with 10, so arr1 should be:
0:[11, 2, 3]
1:[1, 2, 3]
2:[1, 2, 3]
What I did:
arr1[0][0]+=10;
But this way the result is:
0:[11,2,3]
1:[11,2,3]
2:[11,2,3]
What am I missing? Why increments this command all the numbers at position 0 of the array elements?

Because every element of arr1 is the same array, so a change to one is a change to all.

Try this:
var arr1=[];
arr1.push([1,2,3]);
arr1.push([1,2,3]);
arr1.push([1,2,3]);
arr1[0][0]+=10;
That will give you the desired result.
Your issue is that you've got the same reference to an object three times and when you change that object's value, all references to that object will display the updated value.

When you run var arr2=[1,2,3];, It will instantiate an object and assign it to arr2.
When you run arr1.push(arr2), you are pushing a reference to that object assigned to arr2.
In other words, arr1[0] === arr1[1] === arr1[2].
What you need to do is
var arr1=[];
arr1.push([1,2,3]);
arr1.push([1,2,3]);
arr1.push([1,2,3]);

That is happening because you are not pushing a copy of arr2 into arr1, but a reference (pointer) to arr2, which means that you are editing the same array over again.
To avoid that, you should be using spread.
Instead of arr1.push(arr2) do arr1.push([...arr2])
Here is a JSFiddle with output:
0: Array(3) [ 11, 2, 3 ]
​
1: Array(3) [ 1, 2, 3 ]
​
2: Array(3) [ 1, 2, 3 ]

When you assign an array to a variable, you are not making a copy of the array.
let arr1 = [1,2,3];
let arr2 = arr1; // This does NOT create a copy of the array!
console.log(arr1[0]);
arr2[0] = "BOOM!"; // change arr2
console.log(arr1[0]); // displays "BOOM!" not 1 - arr1 is changed, too!
This is because both arr1 and arr2 are pointing to the same array.

Objects (Arrays are Objects too) are passed as references. That means that your array looks like this (pseudostructure):
arr2 -> [1, 2, 3]
arr1 -> [ -> arr2, -> arr2 -> arr2]
Therefore arr1[0] is just the same as arr1[1] or arr2. To create three different arrays copy the array:
arr1.push([...arr2]);

Related

add 1 to a single element in an array

There is an array containing numbers and I want to increment only one number in the array
let array = [1, 3, 5]
// just add 1 in the second element of the array and return that array
// array = [1, 4, 5]
Both array[1]++ and array[1] = array[1] + 1 will work.
If you want you can increment another number using the Push(); method:
let array = [1,2,3];
array.push(yourNumber);

JS - For Loops Pushing Array

I have an initial array,
I've been trying to change values (orders) by using pop, splice methods inside a for loop and finally I push this array to the container array.
However every time initial array is values are pushed. When I wrote console.log(initial) before push method, I can see initial array has been changed but it is not pushed to the container.
I also tried to slow down the process by using settimeout for push method but this didnt work. It is not slowing down. I guess this code is invoked immediately
I would like to learn what is going on here ? Why I have this kind of problem and what is the solution to get rid of that.
function trial(){
let schedulePattern = [];
let initial = [1,3,4,2];
for(let i = 0; i < 3; i++){
let temp = initial.pop();
initial.splice(1,0,temp);
console.log(initial);
schedulePattern.push(initial);
}
return schedulePattern;
}
**Console.log**
(4) [1, 2, 3, 4]
(4) [1, 4, 2, 3]
(4) [1, 3, 4, 2]
(3) [Array(4), Array(4), Array(4)]
0 : (4) [1, 3, 4, 2]
1 : (4) [1, 3, 4, 2]
2 : (4) [1, 3, 4, 2]
length : 3
When you push initial into schedulePattern, it's going to be a bunch of references to the same Array object. You can push a copy of the array instead if you want to preserve its current contents:
schedulePattern.push(initial.slice(0));
Good answer on reference types versus value types here: https://stackoverflow.com/a/13266769/119549
When you push the array to schedulepattern, you are passing a reference to it.
you have to "clone" the array.
use the slice function.
function trial(){
let schedulePattern = [];
let initial = [1,3,4,2];
for(let i = 0; i < 3; i++){
let temp = initial.pop();
initial.splice(1,0,temp);
console.log(initial);
schedulePattern.push(initial.slice());
}
return schedulePattern;
}
​
You have to know that arrays are mutable objects. What does it mean? It means what is happening to you, you are copying the reference of the object and modifying it.
const array = [1,2,3]
const copy = array;
copy.push(4);
console.log(array); // [1, 2, 3, 4]
console.log(copy); // [1, 2, 3, 4]
There are a lot of methods in Javascript which provide you the way you are looking for. In other words, create a new array copy to work properly without modify the root.
const array = [1,2,3]
const copy = Array.from(array);
copy.push(4);
console.log(array); // [1, 2, 3]
console.log(copy); // [1, 2, 3, 4]
I encourage you to take a look at Array methods to increase your knowledge to take the best decision about using the different options you have.

How to remove an item from a list without distorting the original list

This is what I'm trying to do, I have an array
var arr = [1, 2, 3, 4, 5];
then I want to create a new array each time by removing an item once i.e when i remove item at index 0 i should have [2, 3, 4, 5]and when i remove an item at index 1, I should have [1, 3, 4, 5] and so on till i get to arr.length-1 and each time i remove an item i still want my arr to be intact unchanged
using javaScript I have tried some array methods like splice, slice but all that changes the value of arr
how do i go about it with either javascript or python.
For Javascript, using ES6 array spread operator and slice method,
var new_array = [...a.slice(0, index), ...a.slice(index + 1)];
const cut = (a, i) => [...a.slice(0, i), ...a.slice(i + 1)];
let arr = [2, 2, 2, 4, 2];
console.log(cut(arr, 3));
console.log(arr);
For Python:
array = [1,2,3,4,5];
newarray = [value for counter, value in enumerate(array) if counter != 0 ]
PS each time you will use this list-comprehension, array will not be modified! so basically you will get the same output for newarray.
If you want to have newarray each time removed one element you need to create a function instead of list-comprehension (of course it's possible but will likely be less readable).
For JavaScript:
Try making a copy with slice() (slice returns a shallow copy of the array that you can manipulate without affecting the original array) and then using splice() to remove the value at your desired index:
newArray = slice(arr).splice(index, 1);

pushing an array into another array

I have the following arrays.
var arr1=[1,2,3];
var arr2=[4,5,6];
var arr3=[];
How would I push arr1 and arr2 into arr3 such that the result is:
arr3=[[1,2,3],[4,5,6]];
not
arr3=[1,2,3,4,5,6];
which is produced when using the .concat method.
var arr1=[1,2,3];
var arr2=[4,5,6];
var arr3=[];
arr3.push(arr1,arr2);
console.log(arr3);
var arr1=[1,2,3];
var arr2=[4,5,6];
var arr3 = [arr1,arr2];
console.log(arr3);
arr3.push(arr1);
arr3.push(arr2);
will do the work.
Anyway just follow http://www.w3schools.com/jsref/jsref_push.asp for further clarifications.
Hope this helps.
You can use push() like in the other answers or this:
var arr1 = [1,2,3];
var arr2 = [4,5,6];
var arr3 = [arr1, arr2];
console.log(arr3);
As others users have posted, the solution at your problem is use .push() method, but i would try to give you more information about these two methods.
I suggest you to read this article, is very useful for me; I recap the main information for you below.
PUSH METHOD
Push method is used when you want add one or more elements, that were input arguments, to the array that invoked the method.
A simply example is the following:
var first_array = [1, 2, 3];
var result = first_array.push(4, 5, 6);
console.log(result); // 6
console.log(first_array ); // [1, 2, 3, 4, 5, 6]
The one thing is not immediately apparent is that it returns the length of the array after adding the new values, not the modified array. (check third line: console.log(result);)
CONCAT METHOD
While push alters the array that invoked it, concat returns a new array with the original array joined with the array/s or value/s that were provided as arguments.
There are a couple of the things to note about concat and how it creates the returned array.
Both strings and numbers are copied into the array, which means that they if the original value is changed, the value in the new array will be unaffected.
This is not true for objects.
Instead of copying objects into the new array, the references are copied instead. This means that if the values of objects change in one array, they will also be changed in the other array, as they are references to the objects not unique copies.
A simply example is the following:
var test = [1, 2, 3]; // [1, 2, 3]
var example = [{ test: 'test value'}, 'a', 'b', 4, 5];
var concatExample = test.concat(example); // [1, 2, 3, { test: 'test value'}, 'a', 'b', 4, 5]
example[0].test = 'a changed value';
console.log(concatExample[3].test); // Object { test: "a changed value"}
example[1] = 'dog';
console.log(concatExample[4]); // 'a'
I have created a fiddle for you with this example.
I hope that will be helpful

If Array.prototype.slice() method returns shallow copy why does changing the value of sliced array does not change the original

The Array.prototype.slice() method documentation says
The slice() method returns a shallow copy of a portion of an array into a new array object.
If that is the case why does modifying the array returned by the Array.prototype.slice() does not change the original value.
> a = [1, 2, 3]
[ 1, 2, 3 ]
> b = a.slice(0)
[ 1, 2, 3 ]
> b[0] = 4
4
> b
[ 4, 2, 3 ]
> a // the expected output should be the same as output of b if b is shallowcopy of a.
[ 1, 2, 3 ]
May be copy on write is happening while trying to modify the array a. If so is it technically correct to say that Array.prototype.slice() does return shallow copy.
The result of a.slice is a new array, it's not a pointer to the initial variable.

Categories

Resources