0

I'm trying to update every element of a 2d array only once. But unexpectedly array item gets update multiple times.

For example:

const s = "ab";
const m = [...Array(s.length).fill([...Array(s.length).fill("")])]

for(let row = 0; row < s.length; row++) {
  for (let col = 0; col < s.length; col++) {
    console.log(row, col)
    m[row][col] += `<${row}${col}>`
  }
}

console.log(m)

it should return m = [ [ '<00>', '<01>' ], [ '<10>', '<11>' ] ]

but it returns m = [ [ '<00><10>', '<01><11>' ], [ '<00><10>', '<01><11>' ] ] instead.

Can anyone explain it, please?

Update:

Here I'm looping through each item once, so there should be no chance of updating the item twice ( two value should not concat here )

3 Answers 3

1

Instead of initializing array with specific length. You may just initialize empty array then push the elements. Because if you do + of 2 strings, it may just concatenate it, for example:

console.log("I "+"am");

Full working code:

const s = "ab";
let m = [];

for(let row = 0; row < s.length; row++) {
  m.push([]);
  for (let col = 0; col < s.length; col++) {
    m[row].push(`<${row}${col}>`);
  }
}

console.log(m);

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

7 Comments

could you explain what's wrong with my code?
for some reason, I need to initialize the array before starting the loop
Your double fill likely does not create what you think it does
I know plus sign is the problem, but it means somehow array item updating twice, right? but why? @DhanaD.
I think it's because of the fill. Have you tried logging the value of the initialized array before the loop?
|
0

The issue is that you are using <${row}${col}>, You should simple use let size=0 and use Array[i][j] = size++; in place of <${row}${col}>

you should use the following way for 2D Arrays

//Create a new 1D array

let myArray  = new Array(2);

// Loop to create 2D array using 1D array

for (let i = 0; i < myArray.length; i++) {
    myArray[i] = new Array(2);
}

//declare size

let size = 0;

// Loop to initialize 2D array elements.

for (let i = 0; i < 2; i++) {
    for (let j = 0; j < 2; j++) {
        myArray[i][j] = size++;
    }
}

// Loop to display the elements of 2D array.

for (let i = 0; i < 2; i++) {
    for (let j = 0; j < 2; j++)    {
        document.write(myArray[i][j] + " ");
    }
    document.write("<br>");
}

Comments

0

You don't even need a loop, you can use map instead.

const a = Array(2).fill(null).map(
  (_, row) => Array(2).fill(null).map(
    (_, col) => `<${row}${col}>`
  )
);

Comments

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.