0

let s:number[][];

How can I fill this s matrix as 0 of n * n.

[[0, ..., 0], [0, ..., 0] ... [0, ..., 0]]

This is what I'm doing

for(let i = 0;i < n;i ++) {
    let ss = [];
    for(let j = 0;j < n ;j ++)   ss.push(0);
    s.push(ss);
}

It's working but is there any more efficient and sophisticated way?

3 Answers 3

2

You can use Array's fill method:

s = new Array(n).fill(new Array(n).fill(0));
Sign up to request clarification or add additional context in comments.

Comments

1

Try to use the Array.from:

fillTwoDArray = (rows, columns,  defaultValue) => {
      return Array.from({ length:rows }, () => (
          Array.from({ length:columns }, ()=> defaultValue)
       ))
    }

console.log(fillTwoDArray(3, 7, 'foo'))

Comments

1
const s = [...Array(n)].map(e => Array(n).fill(0))

I'm using this way!

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.