Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resize an array

Is there an Array method that can replace the following function (Something like a.splice(some, tricky, arguments))?

function resize(arr, newSize, defaultValue) {
  if (newSize > arr.length)
    while(newSize > arr.length)
      arr.push(defaultValue);
  else
    arr.length = newSize;
}

If not, is there a better / nicer / shorter / implementation? The function should append a default value if the array should grow and remove values on shrink.

like image 375
hansmaad Avatar asked Aug 17 '15 15:08

hansmaad


1 Answers

In terms of elegance, I would say you could trim down your original solution to:

function resize(arr, newSize, defaultValue) {
    while(newSize > arr.length)
        arr.push(defaultValue);
    arr.length = newSize;
}

Or use prototype:

Array.prototype.resize = function(newSize, defaultValue) {
    while(newSize > this.length)
        this.push(defaultValue);
    this.length = newSize;
}

Edit: ES2016 approach:

function resize(arr, newSize, defaultValue) {
    return [ ...arr, ...Array(Math.max(newSize - arr.length, 0)).fill(defaultValue)];
}
like image 178
James Brierley Avatar answered Sep 28 '22 11:09

James Brierley