Languages
[Edit]
EN

JavaScript - resize array

6 points
Created by:
JustMike
27910

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]

< ES6 example

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

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]
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