Languages
[Edit]
EN

TypeScript - resize array

0 points
Created by:
maciek211
425

In this short article, we would like to show how to resize array in TypeScript.

Quick solution (>= ES6):

const resizeArray = (array: number[], newSize: number): number[] => {
  const changeSize = newSize - array.length;
  if (changeSize > 0) {
    return array.concat(Array(changeSize).fill(0));
  }
  return array.slice(0, newSize);
};


// Usage example:

const array: number[] = [1, 2, 3, 4, 5];

const array1: number[] = resizeArray(array, 3);  // new size=3   so: [1, 2, 3]
const array2: number[] = resizeArray(array, 10); // new size=10  so: [1, 2, 3, 4, 5, 6, 0, 0, 0, 0]

console.log(JSON.stringify(array1)); // [1, 2, 3]
console.log(JSON.stringify(array2)); // [1, 2, 3, 4, 5, 6, 0, 0, 0, 0]

Output:

[1,2,3]
[1,2,3,4,5,0,0,0,0,0]

< ES6 example

Sometimes we want to use a solution that works in older TypeScript (< ES6).

Below code shows how to do it:

const createArray = (count: number): number[] => {
  const array = Array(count);
  for (let i = 0; i < count; ++i) {
    array[i] = 0;
  }
  return array;
};

const resizeArray = (array: number[], newSize: number): number[] => {
  const changeSize = newSize - array.length;
  if (changeSize > 0) {
    return array.concat(createArray(changeSize));
  } else {
    return array.slice(0, newSize);
  }
};


// Usage example:

const array: number[] = [1, 2, 3, 4, 5];

const array1: number[] = resizeArray(array, 3);  // new size=3   so: [1, 2, 3]
const array2: number[] = resizeArray(array, 10); // new size=10  so: [1, 2, 3, 4, 5, 6, 0, 0, 0, 0]

console.log(JSON.stringify(array1)); // [1, 2, 3]
console.log(JSON.stringify(array2)); // [1, 2, 3, 4, 5, 6, 0, 0, 0, 0]

Output:

[1,2,3]
[1,2,3,4,5,0,0,0,0,0]
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join