Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

208
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda