EN
JavaScript - resize array
6 points
In this short article, we would like to show how to resize array in JavaScript.
Quick solution (ES6+):
xxxxxxxxxx
1
const resizeArray = (array, newSize) => {
2
const changeSize = newSize - array.length;
3
if (changeSize > 0) {
4
return array.concat(Array(changeSize).fill(0));
5
}
6
return array.slice(0, newSize);
7
};
8
9
10
// Usage example:
11
12
const array = [1, 2, 3, 4, 5];
13
14
const array1 = resizeArray(array, 3); // new size=3 so: [1, 2, 3]
15
const array2 = resizeArray(array, 10); // new size=10 so: [1, 2, 3, 4, 5, 6, 0, 0, 0, 0]
16
17
console.log(JSON.stringify(array1)); // [1, 2, 3]
18
console.log(JSON.stringify(array2)); // [1, 2, 3, 4, 5, 6, 0, 0, 0, 0]
Sometimes we want to use a solution that works in older JavaScript (ES5).
The below code shows how to do it:
xxxxxxxxxx
1
function createArray(count) {
2
var array = Array(count);
3
for (var i = 0; i < count; ++i) {
4
array[i] = 0;
5
}
6
return array;
7
}
8
9
function resizeArray(array, newSize) {
10
var changeSize = newSize - array.length;
11
if (changeSize > 0) {
12
return array.concat(createArray(changeSize));
13
} else {
14
return array.slice(0, newSize);
15
}
16
}
17
18
19
// Usage example:
20
21
var array = [1, 2, 3, 4, 5];
22
23
var array1 = resizeArray(array, 3); // new size=3 so: [1, 2, 3]
24
var array2 = resizeArray(array, 10); // new size=10 so: [1, 2, 3, 4, 5, 6, 0, 0, 0, 0]
25
26
console.log(JSON.stringify(array1)); // [1, 2, 3]
27
console.log(JSON.stringify(array2)); // [1, 2, 3, 4, 5, 6, 0, 0, 0, 0]