Home > Mobile >  How to extend a given array with default values?
How to extend a given array with default values?

Time:02-19

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?

CodePudding user response:

As already said in the comments. fill does not add new elements.

The fill() method changes all elements in an array to a static value, from a start index (default 0) to an end index (default array.length). It returns the modified array.

You could change the .length before you call fill:

let array = [true, false, true];

const amountOfNewItems = 3;

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

console.log(array);

CodePudding user response:

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);

CodePudding user response:

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));
  
  
  

  • Related