Search code examples
javascriptmultidimensional-arrayarray-merge

Deep Merge of Arrays in Vanilla Js not working as expected


I made a codepen to demonstrate my Problem: https://codepen.io/milenoi-the-sans/pen/vYmzyOj

I have a object that contains several arrays.

I want to change some values in the array by clicking on buttons.

My Problem: The Code works as expected using

   $series = $.extend(true, [], arr[2]);

But not in Vanilla JS using

$series = [...[], ...arr[2]];

I want to change a value onclick by multiplying it with a number.

What am i doing wrong?

Thank you!

let arr = {
  2: [{
    label: "Label 1",
    data: [
      [1627776000000, 100]
    ]
  }]
}

let series = null;

let update = function(count) {
  //$series = [...[], ...arr[2]];
  //$series = $.extend(true, [], arr[2]);
  $series = [...arr[2]];

  $series.forEach(($el, index) => {
    let $value = 0;

    $series[index].data.forEach(($ele, subIndex) => {
      $value = $series[index].data[subIndex][1];
      $value = count * $value;
      $series[index].data[subIndex][1] = $value;
    });
    document.querySelector('.text').textContent = $value;

  });

};

document.querySelectorAll('button').forEach(($button) => {
  $button.addEventListener('click', function(e) {
    e.preventDefault();
    update(this.getAttribute('data-count'));
  }, false);
});
.text {
  background: cornflowerblue;
  padding: 30px;
  color: white;
  margin: 10px;
}

button {
  margin: 10px;
}
<button data-count="2">Factor 2</button>
<button data-count="3">Factor 3</button>
<button data-count="4">Factor 4</button>
<button data-count="5">Factor 5</button>

<div class="text"></div>

Expected Output

Clicking on Button should multiply 100 with value of date-count (2,3,4...) so i expect

200 300 400

works on first click. but then it multiplies with the given value.

When i replace $series = $.extend(true, [], arr[2]);

it works as expected.


Solution

  • you change reference array variable. for copy not reference variable you can use

    $series = JSON.parse(JSON.stringify(arr[2]))