Languages
[Edit]
EN

JavaScript - resize array

6 points
Created by:
Walter
586

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]

 

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