Reputation: 104
So what I have is an array, like following
[[1,2],[2,3],[3,4]]
I want to do the computation on the array without changing the original array elements.
i tried slice()
, Array.from()
and [...arr]
also.
The issue is that the original array also changes with the new array.
Please suggest what is missing in the code below.
var arr = [
[1, 2],
[2, 3],
[3, 4]
];
function clicked() {
var scale = 1.1;
var newArray = arr.slice();
newArray.forEach(element => {
var x = element[0];
var y = element[1];
newX = x * scale;
newY = y * scale
element[0] = newX;
element[1] = newY;
});
console.log('New Array: ', newArray);
console.log('Old Array: ', arr);
}
document.querySelector('#click').addEventListener('click', function() {
clicked();
});
<button class="click" id="click"> Click me and check Console</button>
Upvotes: 0
Views: 42
Reputation: 602
use
JSON.parse(JSON.stringify(arr));
It is minimal but please note that it only works for strings, numbers, booleans and a few limited dasta types.
Upvotes: 0
Reputation: 20616
Slice does not do deep-copy. You will have to do it manually.
let newArr = arr.map((x)=>{
return [x[0],x[1]];
});
newArr
is your copy and you can modify it without worrying about arr
.
Upvotes: 0
Reputation: 30705
I would suggest using Array.map to produce the desired result, once for each array in arr
, and again for each element in this array.
var arr = [
[1, 2],
[2, 3],
[3, 4]
];
function clicked() {
var scale = 1.1;
var newArray = arr.map(element => element.map(e => e *= scale));
console.log('New Array: ', newArray);
console.log('Old Array: ', arr);
}
document.querySelector('#click').addEventListener('click', function() {
clicked();
});
<button class="click" id="click"> Click me and check Console</button>
Upvotes: 1
Reputation: 19851
Each element in the array it also an array and in the forEach
function you are changing the internal array by assigning values to 0th
and 1st
indices.
You can create new array by using map
on both outer and inner arrays:
var newArray = arr.map(items => items.map(item => item * scale));
Upvotes: 1