javascriptarraysdeep-copyshallow-copy

shallow copying an array of an array


I have an array with child arrays. I'd want to shift the first element in the first child array (arr[0].shift). But my code below shifts all first elements for all child arrays.

I figure it has something to do with fillWith being a deep-copy, but I've tried in every way I know to make it a shallow copy instead..

What am I missing?

let arr= Array(3)        
let fillWith = Array.from({length: 5}, (_, i) => i+1);

arr.fill([...[], ...fillWith]) // Try 1
//arr.fill(fillWith.slice()) // Try 2


console.log(arr) // -> [[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]]

arr[0].shift();

console.log(arr)
/* 
How I want it to be -> [[2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]]
What it actually becomes -> [[2, 3, 4, 5], [2, 3, 4, 5], [2, 3, 4, 5]]
*/

Solution

  • You might do it like this:

    const fillWith = () => Array.from({length: 5}, (_, i) => i + 1);
    
    const arr = Array.from({length: 3}, fillWith)
    
    console.log(JSON.stringify(arr))
    
    arr[0].shift();
    
    console.log(JSON.stringify(arr))