javascriptarrays

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.


Solution

  • 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)];
    }