Home > front end >  Removing element from an array of arrays of arrays using the splice method in javascript
Removing element from an array of arrays of arrays using the splice method in javascript

Time:05-22

I have an array of arrays of arrays and I'm trying to remove an element from a sub-sub array. The problem is the element is removed from all my sub-sub arrays. See code below:

let list = Array(9).fill(Array(9).fill([1,2,3,4,5,6,7,8,9]));
list[0][0].splice(3,1);
console.log(list[0][0],list[2][1],list)

Please let me know if you know how to solve that.

CodePudding user response:

Array.prototype.fill fills the array with the exact same value that was provided to it. This is not a problem when filling the array with immutable values (like numbers, strings) but it's usually a problem with mutable values (like objects, arrays).

So, if you mutate one value in the array you would notice the change at all other places because all of them refer to the exact same value. Refer to example below for better understanding.

let nums = [1];
let arr = Array(2).fill(nums);

// mutating nums
nums[0] = 5;
// the change is visible in arr as well
console.log(arr[0]); // [ 5 ]
// and it's visible at both the indicies
console.log(arr[1]); // [ 5 ]

// mutating arr
arr[0][0] = 10;
// change is visible in nums as well
console.log(nums); // [ 10 ]
// and also at index 1
console.log(arr[1]); // [ 10 ]

You can use Array.from instead.

let list = Array.from({ length: 9 }, () =>
  Array.from({ length: 9 }, () => [1, 2, 3, 4, 5, 6, 7, 8, 9])
);
list[0][0].splice(3, 1);
console.log(list[0][0]); // [ 1, 2, 3, 5, 6, 7, 8, 9 ]
console.log(list[1][0]); // [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]

  • Related