0

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>

1
  • Try this newArray=array.map(e=>[e[0]*scale,e[1]*scale]) Commented Jun 30, 2021 at 6:33

4 Answers 4

1

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>

Sign up to request clarification or add additional context in comments.

Comments

1

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));

Comments

0

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.

Comments

0

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.

1 Comment

While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.