Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

211
Visualizações
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?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

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

about 4 years ago · Juan Pablo Isaza Relatório

0

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

about 4 years ago · Juan Pablo Isaza Relatório

0

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda