Javascript copying an array of arrays [duplicate] - javascript

This question already has answers here:
Create copy of multi-dimensional array, not reference - JavaScript
(4 answers)
Closed 8 months ago.
I want to copy an array of arrays at a different allocation.
I know that I can copy an array in the following way:
a = [[1, 2], [3, 4]]
b = a.slice() // this makes sure that a and b are allocated differently in memory
Now if I change something inside b, then of course,
b[0] = 'abc'
console.log(a, b) // expect a = [[1,2], [3,4]] and b = ['abc', [3,4]]
But when I do the below, a gets changed as well...!
b[0][0] = 'abc'
console.log(a, b) // now it gives a = [['abc', 2], [3, 4]] and b = [['abc', 2], [3, 4]]
Why is this happening, and how can I avoid mutating a?
Thanks so much!

If you know you are only copying 2D arrays you could use a function like the following and avoid using JSON:
function copy2D(array){
result = []
array.forEach((subArray) => {
result.push(subArray.slice())
})
return result
}

One way would be by using map combined with the spread operator. This would be the easiest approach if you can assume that you have a 2D array only
const a = [[1, 2], [3, 4]]
const b= a.map(item => ([...item]))
b[0][0]= "abc"
console.log('a:', a, 'b: ', b)

Related

how to get values from an json array

Guys this might be a simple question, but please help.
i have a data.
var a = { "data":[[1,2,3],[2,4,3],[3,6,7],[1,4],[6,4,3,4],[6,7,3,5]] }
i'm plotting a multiple line chart using chartjs and i want these valus in array to use as datasets.
what i wat is to save each array in different var's
like;
var a = [1,2,3],
var b = [2,4,3]
var c = [3,6,7]
so that i can pass theese values to chart js and plot chart. any help is appreciated. i thought of foreach and getting by each position. but its not working.
regards
Use Array destructuring.
Use spread operator on last node. That will keep all the remaining nodes except the specified number of paramaters, if you are interested on the frst three nodes only.
var data = { "data": [[1, 2, 3], [2, 4, 3], [3, 6, 7], [1, 4], [6, 4, 3, 4], [6, 7, 3, 5]] }
const [a, b, c, ...restNodes] = data.data;
console.log(a);
console.log(b);
console.log(c);
console.log(restNodes);
Please Note Its not mandatory to have the last node with spread operator. You can pick the first three nodes only using
const [a, b, c] = data.data;
I just said you can do this aswell
Spread the data and just assign to three variables.
var x = { "data":[[1,2,3],[2,4,3],[3,6,7],[1,4],[6,4,3,4],[6,7,3,5]] }
let [a,b,c] = [...x.data];
console.log(a);
console.log(b);
console.log(c);
There is no need to even include a fourth variable if all you care about is a,b,c.

Is there a more efficient way to remove all values from list a, which are present in list b? [duplicate]

This question already has answers here:
How to get the difference between two arrays in JavaScript?
(84 answers)
Closed 1 year ago.
This is what I have
function array_diff_very_fast(a, b) {
a = a.filter( el => !b.includes( el ) );
return a;
}
var temp = array_diff_very_fast([1,2,2,2,2,4,5,6], [1,2,6]);
console.log(temp);
and I want it to return [4,5].
I am working in code wars and the function works but it is not efficient enough.
You could take an approach with O(1) for searching the element in a data set, like a Set or an object.
Then omit using a variable just for storing a return value.
function array_diff_very_fast(a, b) {
const bb = new Set(b);
return a.filter(el => !bb.has(el));
}
console.log(array_diff_very_fast([1, 2, 2, 2, 2, 4, 5, 6], [1, 2, 6]));

Can I destructure an array in a Javascript arrow function? [duplicate]

This question already has an answer here:
Destructure an array parameter [duplicate]
(1 answer)
Closed 2 years ago.
Does any version of Javascript support destructuring of arrays in arrow functions? E.g.
const items = [ [1, 2], [3, 4] ];
const sums = items.map( [a, b] => a + b );
You can, but you have to surround the parameter in parentheses:
const items = [ [1, 2], [3, 4] ];
const sums = items.map(([a, b]) => a + b );
console.log(sums);

Choose if array element repeats itself twice -- Javascript [duplicate]

This question already has answers here:
Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array
(97 answers)
Closed 6 years ago.
There is a javascript array
var arr = [0, 1, 2, 2, 3, 3, 5];
I want to choose elements that repeats twice. In this case its 2 and 3. and i want attach them into a variable.
var a = 2, b = 3;
As far as i know there is no built-in function to do that job. How can i do that. Thanks.
You can use filter to get the values that occur twice.
var arr = [0, 1, 2, 2, 3, 3, 5];
var dups = arr.filter ( (v,i,a) => a.indexOf(v) < i );
console.log(dups);
In comments you stated you would only have doubles, but no values that occur more than twice. Note that the above would return a value more than once, if the latter would be the case.
This returns the values in an array, which is how you should work. To put them in separate values can be done as follows:
var [a, b, ...others] = dups;
...but you would have to know how many variables to reserve for that, and it does not make your further program any easier. JavaScript has many nice functions (methods) for arrays, so you should in fact leave them in an array.
There is no built in function to do that indeed.
You will have to loop thought the array and keeping track of the number of occurrences of the elements, while building a response array.
You could filter a sorted array.
var arr = [0, 1, 2, 2, 3, 3, 5],
repeats = arr.filter(function (a, i, aa) {
return aa[i - 1] === a;
});
console.log(repeats);
Most simple way to do this is the following:
var dups = [];
var arr = [0, 1, 2, 2, 3, 3, 5];
arr.forEach(function (v, i, a){
delete arr[i];
if (arr.indexOf(v) !== -1){
dups.push(v);
}
});
console.log(dups);
It's destructive however.

Why do objects changed in function change what they point to in memory, but sometimes create a new memory object? [duplicate]

This question already has answers here:
JavaScript by reference vs. by value [duplicate]
(4 answers)
Closed 8 years ago.
I was reading on this blog about how if an object or array were changed inside of a function, the value in memory that was pointed to would be changed as well, the same as if it were changed outside the function.
var a = [1,2,3],
b = a;
b[0] = 5;
console.log(a); // [5, 2, 3]
would result in the same as
var a = [1,2,3],
b = a;
var arrayFunction = function(arr){
arr[0] = 10;
};
var arr = arrayFunction(b);
console.log(a, b, arr) // [10, 2, 3], [10, 2, 3], [10, 2, 3];
Yet what I can't understand is why reassigning multiple array values within the function does not change the values outside of it:
var a = [1,2,3],
b = a;
var arrayFunction = function(arr){
arr = ["a", "b", "c"];
return arr;
};
var result = arrayFunction(b);
console.log(result) //["a", "b", "c"]
console.log(a, b); //[1, 2, 3], [1, 2, 3]
Why does this not change the pointed to value in memory like in the first example?
Probably a better job of writing out the examples on the JSBIN
This is because objects in javascript aren't really passed by reference. I've seen it referred to as "passed by copied reference", or "passed by handle" - both of which do a better job of describing what's really happening.
In this example:
var b = [1, 2, 3];
var arrayFunction = function(arr) {
arr = ["a", "b", "c"];
};
arrayFunction(b);
The object reference itself is passed by value. You're not actually changing the value of the b variable. However, your function argument (arr) and the b variable are initially pointing to the same object - so if you change one, you can reference the object through either and see the change.
When you reassign arr to point to a different object though, the b variable is still pointing to the old object, and does not change.
Remember that, within the function, arr is not the actual array; arr is a reference that points to the array.
So when you say arr[0], you're retrieving the array, and then getting or updating an item in it.
But when you say arr = ["a","b","c"], you are creating a new object (on the right side) and then turning arr into a reference that points to the new object.
In Javascript a variable merely points to an array; so if you copy the variable you get two variables pointing to the same array:
var a = [1,2,3];
var b = a;
Changing an element of the array with a[0] = 99 will be observable with both variables because there is just one array and both a and b are pointing to it.
When you write instead
a = [5, 6, 7];
you are setting a to point to another different array.
Javascript never makes a copy of an array unless you ask it explicitly (e.g. with b = a.slice()).
Actually the very same happens with any value (objects for example). With numbers and string the same logic is also valid, but it's hard to notice the difference between a copy and sharing the same object because numbers and strings cannot be changed (the're "immutable").
In other languages like C and C++ instead variables contain the value, not a pointer; so when making an assignment for example objects are copied from one variable to the other and if you want a pointer you've to ask explicitly for it.

Categories

Resources