• Register

This is a way of creating an immutable copy of a 2 dimensional array in js if you want to mutate the second array without affecting the original.

Steps (assuming you already have a “board[]” array created)

// Create original array
let board = [[], [], [], [], [], []];

// Get copy of original array
let c0 = board[0].slice();
let c1 = board[1].slice();
let c2 = board[2].slice();
let c3 = board[3].slice();
let c4 = board[4].slice();
let c5 = board[5].slice();

let boardCopy = [c0.slice(), c1.slice(), c2.slice(), c3.slice(), c4.slice(), c5.slice()];

// Now you can modify "boardCopy" without affecting "board" at all

1. Store each array inside the ‘board’ array into a variable using the “slice()” function.

2. Create another variable “boardCopy” which is an array that stores all the previous variables we created, also use the “slice()” function.

3. Done! “boardCopy” is now a seperate array from “board” but with the same value and won’t affect the first array when mutated. This can also be done with higher dimensional arrays just by using the same logic.

More Posts

Converting 2D array to 1D Michel Maalouly - Sep 15, 2020
Find largest and smallest number in an array in java Tania - Jul 11
Comparing two arrays in javascript returning differences Sanjana Sagar - May 19
How to declare two dimensional array using pointers in c-C++ hhh98hd - 16 hours
C program to find sum of even and odd numbers in an array Tania - Jul 18
Find the Size of an array in C++ Faizan - Oct 20, 2020
How to make a hangman game in javascript (Part 2) amna - Oct 18, 2020
how to initialize a 2d array in java Hasnain_khan - Oct 11, 2020
How to remove elements from an array in javaScript sakshi - May 25
In JavaScript, how to check if an array is empty, null, or undefined. muliemes - May 4