Javascript - pass variable by reference issue - javascript

I am trying to make a copy of a javascript array and modify the 'copy' without modifying the original variable too, can anyone explain what I am doing wrong..
e.g
var array1 = [2, 5];
var array2 = '';
array2 = array1;
array2.pop();
console.log(array1);
console.log(array2);
// both output the same, however I want it to show array1 with 1 single item
I am trying to make it so array2 will only contain the one item in the array & array1 will contain two items in the array. Any ideas what I'm doing wrong?

In order to create a copy of an array rather than assign the reference value you can use the .slice method.
array2 = array1.slice(0);
Slice returns a (shallow) copy of the given array from the given index to the (optional end index)

Use slice() to copy the array.
var array1 = [2, 5];
var array2 = '';
array2 = array1.slice(0);
array2.pop();
console.log(array1);
console.log(array2);
slice does not alter the original array, but returns a new "one level
deep" copy that contains copies of the elements sliced from the
original array.
Documentation

It is as simple as using the slice function:
var array1 = [2, 5];
var array2 = '';
array2 = array1.slice();
array2.pop();
console.log(array1);
console.log(array2);
Here you are telling javascript to get a copy of the elements in array1 and assign the result to array2. By not setting the start and ending position it will slice the whole array.

When you writing this
array2 = array1 //It creates reference on array1 object
array2.pop() // removes 5 from both end
So you have to clone one array to another by slice() method---
array2 = array1.slice(0) // cloning array1 's element to array2
array2.pop() // removes 5 from only array2 not from array1
Now it works fine

Alter the line array2 = array1; to:
array2 = array1.slice(0);
Slice method returns a (shallow) copy of the given array from the given index to the (optional end index)
I hope this helps.

Related

Copy an array into the middle of a larger array in Javascript

I've searched through the answers here, but I can only find this question answered for other languages.
So I have 2 Uint8 typed arrays.
var arr1 = [0,0,0];
var arr2 = [0,1,2,3,4,5,6,7,8,9];
I want to replace the contents of arr2 with arr1 starting at the 4th position. So that arr2 will be:
arr2 = [0,1,2,0,0,0,6,7,8,9];
If I wasn't trying to do this in the middle of the array I could use set like this:
arr2.set(arr1);
And I would get:
arr2 = [0,0,0,4,5,6,7,8,9];
I know I can loop through the arr2 and individually copy the values, but performance wise this is very slow compared to set (and performance matters to me because it's copying an entire array of canvas img data 24 times a second).
Is there any function that can copy into the middle of an array, but with the performance of set?
Use the typedarray.set(array[, offset]) offset.
offset Optional
The offset into the target array at which to begin
writing values from the source array. If you omit this value, 0 is
assumed (that is, the source array will overwrite values in the target
array starting at index 0).
const arr1 = new Uint8Array([0,0,0]);
const arr2 = new Uint8Array([0,1,2,3,4,5,6,7,8,9]);
arr2.set(arr1, 4);
console.log(arr2);
You can use the slice method with the spread syntax:
const shim = (source, index, target) => [
...source.slice(0, index),
...target,
...source.slice(index)
]
var arr1 = [0,0,0];
var arr2 = [0,1,2,3,4,5,6,7,8,9];
const newArr = shim(arr2, 3, arr1);
console.log(newArr);
.slice will not mutate the array and will return a new shallow copy of it (unlike splice).
Since you are using typed array. Don't you can use the offset of the set method?
arr2.set(arr1, 3)
To overwrite from the 4th element of the target array.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/set
To me it does just what you need, if I understand your question.

how to create 2D array in javascript (dynamic)

var array1 = ["james","bob"];
var array2 = ["name","age"];
i had created let us say two arrays array1 and array2. what i'm doing is now for every element in array1 i want a new array of length 5 for that. for example for "james" i want an array of length 5 and for "bob" i want array if length 5 only. Also array1 is dynamic, not static. How to achieve that?
You can use array#reduce. Reduce will iterate for each name in your array1 and you have aggregator newarr where code will keep inserting an array of 5 elements using newarr.push(Array(5))(Array(5) is a constructor to create an array of 5 elements);
In case you want to give default value you can use array#fill()
var array1 = ["james","bob"];
var newarr = array1.reduce((newarr, name) => {
newarr.push(Array(5));
return newarr;
},[]);
console.log(newarr);

Adding array of arrays dynamically in javascript

I am trying to add array of arrays dynamically in javascript. I need the data in the following format -
var dataArray = [[],[],[],.....,[]];
How can I initialize this kind of array? Suppose if I have three arrays to be added, I can initialize as follows -
var dataArray = [[],[],[]];
This will accept only three records to be added. But, what should I do in case of adding large number of arrays? Here I cannot know the amount of data I get as input.
I have tried using concat() and merge() methods, these are adding contents directly in to a single array, but that is not what I wanted.
Can any one please help me out on this?
You can build or add an array into an array like this:
var dataArray = [];
dataArray.push([1,2,3]);
dataArray.push([3,4,5]);
console.log(dataArray); // [[1,2,3], [3,4,5]]
Or, if you want to add elements to the sub-arrays:
var dataArray = [];
dataArray.push([1,2,3]);
dataArray.push([3,4,5]);
dataArray[0].push(4);
dataArray[1].push(9);
console.log(dataArray); // [[1,2,3,4], [3,4,5,9]]
You initialize a sub-array by assigning an array to the element of the outer array. You can then use array operations directly on the sub-array element:
// create a sub-array element
dataArray[2] = [];
dataArray[2].push(8);
dataArray[2].push(7);
console.log(dataArray[2]); // [8,7]
console.log(dataArray); // [[1,2,3,4], [3,4,5,9], [8,7]]
The key thing it appears you don't understand is that an array of arrays is just that. It's an outer array where each element in the outer array is itself an array. You use ordinary array methods to operate on either the outer array or the inner arrays. To operate on an inner array, you fetch that element from the outer array and then just treat it as an array. For example:
var dataArray = [];
dataArray.push([1,2,3]);
dataArray.push([3,4,5]);
console.log(dataArray); // [[1,2,3], [3,4,5]]
var innerArray = dataArray[0];
console.log(innerArray); // [1,2,3]
innerArray.push(12);
console.log(innerArray); // [1,2,3,12]
innerArray.legnth = 2;
console.log(innerArray); // [1,2]
innerArray.push(9,8,7);
console.log(innerArray); // [1,2,9,8,7]
innerArray.splice(1,2);
console.log(innerArray); // [1,8,7]
You have wrote "I am trying to add array of arrays dynamically in javascript"
The simple way is using Array.prototype.push method:
var arr1 = [1,2], arr2 = [3,4], arr3 = [5,6], arr4 = [7,8], arr5 = [9,10],
dataArray = [];
[].push.apply(dataArray, [arr1, arr2, arr3, arr4, arr5]);
console.log(JSON.stringify(dataArray, 0, 4));
The console.log output:
[
[
1,
2
],
[
3,
4
],
[
5,
6
],
[
7,
8
],
[
9,
10
]
]
There are tons of way you can do this. A simple one could be
var arrayN = n => Array(n).fill([])
document.write("<pre>" + JSON.stringify(arrayN(10)) + "</pre>")
On another thinking if you already have arrays of arrays then the most simplified way of concatenating them in place should be using the new spread operator like;
var arr = [[1,2,3],[1,3,5]],
brr = [[3,2,1],[7,8,9]];
arr.push(...brr);
document.write("<pre>" + JSON.stringify(arr) + "</pre>");

Comparing two arrays using javascript

var array1 = [column1,column2,column3,column4];
var array2 = [column1 [empid],column2 [mobno],column4 [place]];
if array1 has any of array2 values. I mean, in above case column1,column2,column4 is there in array1, then remove those values and array1 should have only column3 and then append array1 value with array2.
after check and remove, now array1 = [column3] then append array1 value with array2 and finally
array2 = [column1 [empid],column2 [mobno],column3,column4 [place]]; it should be in correct index position
is above case possible?
I would recommend using a library like Underscore.js, it has functions like _.union() that would do what you described. If you don't want to the library you could have a look at their implementation.
Using your example:
array2 = _.union(array1, array2);
if you dont want to use any library then you can do
for(elem in array2){
var index = array1.indexOf(array2[elem]);
if(index > -1)
array1.splice(index,1);
}
array2 = array1.concat(array2).sort();

using splice(0) to duplicate arrays

I have two arrays: ArrayA and ArrayB. I need to copy ArrayA into ArrayB (as opposed to create a reference) and I've been using .splice(0) but I noticed that it seems to removes the elements from the initial array.
In the console, when I run this code:
var ArrayA = [];
var ArrayB = [];
ArrayA.push(1);
ArrayA.push(2);
ArrayB = ArrayA.splice(0);
alert(ArrayA.length);
the alert shows 0. What am I doing wrong with .splice(0)??
Thanks for your insight.
You want to use slice() (MDN docu) and not splice() (MDN docu)!
ArrayB = ArrayA.slice(0);
slice() leaves the original array untouched and just creates a copy.
splice() on the other hand just modifies the original array by inserting or deleting elements.
splice(0) grabs all the items from 0 onwards (i.e. until the last one, i.e. all of them), removes them from the original array and returns them.
You are looking for slice:
var a = [1,2,3,4,5]
,b = a.slice();
//=> a = [1,2,3,4,5], b = [1,2,3,4,5]
you can use splice, but it will destroy your original array:
var a = [1,2,3,4,5]
,b = a.splice(0);
//=> a = [], b = [1,2,3,4,5]

Categories