1

I am working on something in javascript where I need to create a matrix with dynamic dimensions depending upon an array.

For example, I have an array with [3, 5, 6] - now I want to create a matrix dynamically that is 3 x 5 x 6, and in this matrix, all the values are initialized to 0.

I can seem to find a way to do this dynamically depending upon my initial array values. Anyone have any idea?

1
  • Just use a recursive function with for loops Commented Jun 23, 2021 at 1:03

2 Answers 2

3

A recursive function that uses Array.from will do the trick.

const makeMatrix = (length, ...restDimensionLengths) => Array.from(
  { length },
  () => restDimensionLengths.length ? makeMatrix(...restDimensionLengths) : 0
);

console.log(makeMatrix(2, 3, 5));

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

2 Comments

is there a way i can do this without arrow notation?
Just use function() { return instead of () => ??
2

You can use recursion.

function createMatrix(dimensions) {
  return dimensions.length === 1 ? Array(dimensions[0]).fill(0) : Array.from({
    length: dimensions[0]
  }, () => createMatrix(dimensions.slice(1)));
}
console.log(JSON.stringify(createMatrix([3, 5, 6])));

6 Comments

is there a way i can do this without arrow notation?
@SnG Yes, you can use function(){return createMatrix(dimensions.slice(1))}
this is an unrelated question, but in my example I can have N dimensions based on the input. Is there a way I can programmatically index the N dimensional matrix given an array of indexes?
@SnG indexes.reduce((acc,i)=>acc[i], matrix)
Get the second last element you need using reduce, and set the last index on that.
|

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.