'How to extend a given array with default values?

I have an array holding a bunch of booleans and a function that adds n new booleans to it. All of them should start with their default value, so one way would be

const array = [];

function extendArrayBy(amountOfNewItems) {
  for (let i = 0; i < amountOfNewItems; i++) {
    array.push(false);
  }
}

extendArrayBy(3);

console.log(array);

but there is a Array.prototype.fill() function which might do it "more elegant". What I tried:

let array = [];

const amountOfNewItems = 3;

array = array.fill(false, array.length, array.length + amountOfNewItems);

console.log(array);

Unfortunately the modified array does not contain the new items. Does someone know what I missed?



Solution 1:[1]

Give this a try:

let amountOfNewItems = 3;

let array = [];

array = array.concat(Array(amountOfNewItems).fill(false));
console.log(array);

let array2 = [1,2,3];

array2 = array2.concat(Array(amountOfNewItems).fill(false));
console.log(array2);

Solution 2:[2]

Here's a function that extends an array with a given value by a given amount.

let arr = ['A', 1, {k: 'v'}];

/** Extends an array with a given *** value at a given amount.
* @param  {Array}  array
* @param  {Any}    element
* @param  {Number} size
* @return {Array}
*/
const extend = (array, element, size = 1) => {
  let extra = element == undefined ? null : element;
  const extArr = [...new Array(size)].map(e => extra); 
  return [...array, ...extArr];
};

console.log(extend(arr, false, 7));
  
  
  

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 James
Solution 2 zer00ne