EN
JavaScript - resize array
6
points
In this short article, we would like to show how to resize array in JavaScript.
Quick solution (ES6+):
// ONLINE-RUNNER:browser;
const resizeArray = (array, newSize) => {
const changeSize = newSize - array.length;
if (changeSize > 0) {
return array.concat(Array(changeSize).fill(0));
}
return array.slice(0, newSize);
};
// Usage example:
const array = [1, 2, 3, 4, 5];
const array1 = resizeArray(array, 3); // new size=3 so: [1, 2, 3]
const array2 = 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]
ES5 example
Sometimes we want to use a solution that works in older JavaScript (ES5).
The below code shows how to do it:
// ONLINE-RUNNER:browser;
function createArray(count) {
var array = Array(count);
for (var i = 0; i < count; ++i) {
array[i] = 0;
}
return array;
}
function resizeArray(array, newSize) {
var changeSize = newSize - array.length;
if (changeSize > 0) {
return array.concat(createArray(changeSize));
} else {
return array.slice(0, newSize);
}
}
// Usage example:
var array = [1, 2, 3, 4, 5];
var array1 = resizeArray(array, 3); // new size=3 so: [1, 2, 3]
var array2 = 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]