1

Using typescript, I would like to initialize a 2D empty array with specific length and number type. We can create a 1D array like this:

 const test: Array<number> = new Array(5);

Like this, I will have an empty array of 5 elements. But how could I do with 2D dimensions without using a loop ?

Indeed, I know that in Java it is possible to do something like that:

int[][] multi = new int[5][10];

This will create a 2D array 5x10. I would like to do something similar in typescript.

2
  • You can't do it without a loop (sort of, some methods will internally loop). But do you really need the array to be initialised with some length? Because new Array(5) pretty much does nothing, it just sets the length property of the array and that's it. It doesn't reserve space for the array or anything and you can always add more stuff. Moreover, you can't even map or use any of the similar array methods, since all of those are empty slots which are skipped. Commented Oct 21, 2019 at 7:23
  • Yes, I need it because after that, I have to access to the element test[2][5] and then test[1][3], ... no specific order Commented Oct 21, 2019 at 7:50

2 Answers 2

1

You can't do it without a loop. However, the easiest way to get a 2D array is using Array.from - create an array with your desired length and generate a new array for each of its members:

const test = Array.from({length: 5}, () => Array.from({length: 10}));

console.log(test);

This can be generalised to work for N-dimensional arrays by employing recursion

function makeNDArray(...sizesPerLevel) {
  if (sizesPerLevel.length === 0) return; //terminal condition
  
  const [thisLevelSize, ...restSizes] = sizesPerLevel;
  
  return Array.from({length: thisLevelSize}, () => makeNDArray(...restSizes))
}

console.log(makeNDArray(5, 10));
console.log(makeNDArray(3, 5, 8));

This can be further shortened by using destructuring straight in the parameters but it makes the signature harder to read:

/**
 * generates N-dimensional where all values are `undefined`
 * @param {...number} varargs of sizes for each level of the array
 */
function makeNDArray(...[thisLevelSize, ...restSizes]) {
  if (!thisLevelSize) return; //terminal condition
  
  return Array.from({length: thisLevelSize}, () => makeNDArray(...restSizes))
}

console.log(makeNDArray(5, 10));
console.log(makeNDArray(3, 5, 8));

If you want to initialise each member with something custom rather than undefined, then you can pass an extra parameter for what that would be.

/**
 * generates N-dimensional where all values are `undefined`
 * @param {function|any} function that will supply the default value in each array or the value to be put as each member of the arrays
 * @param {...number} varargs of sizes for each level of the array
 */
function makeNDArray(value, ...[thisLevelSize, ...restSizes]) {
  let valueProducer;
  
  if (typeof value === "function") {
    valueProducer = value;
  } else { //make into a producer function
    valueProducer = () => value;
  }
  
  //terminal condition
  if (!thisLevelSize) return valueProducer();
  
  return Array.from({length: thisLevelSize}, () => makeNDArray(valueProducer, ...restSizes))
}

const fillWithNull = makeNDArray(null, 2, 2);
console.log(fillWithNull);

const fillWithArrays = makeNDArray(() => [], 2, 2);
fillWithArrays[0][0].push("hello");
fillWithArrays[0][1].push("world");
console.log(fillWithArrays);

I've it's best for that parameter to be a function, otherwise if you try to fill the array with an object, you'll get a copy of the same object for all members, so changing one will affect all. However, you can use a fallback for simple values, so you don't have to pass in () => 42.

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

Comments

1

Try to create multidimensional array like this:

twoArray = new Array(new Array(5), new  Array(5));

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.