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

146
Visualizações
Replacing empty/undefined values with nulls in JavaScript array

I have an array and I want to convert the empty/undefined values to null. I have tried the following:

let arr = []
arr[1] = 2
arr[7] = 10
arr = arr.map(x => x || null)

console.log(arr)

But the output of the snippet is not as desired:

[ undefined, 2, undefined, undefined, undefined, undefined, undefined, 10 ]

How do I replace these undefined values with nulls? TIA

Note: Both vanilla JS and lodash answers are acceptable.

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

0

What you have will work for an array that has undefined elements in it, but not for a sparse array with holes in it, because map doesn't visit the holes in a sparse array; instead, the resulting array just has holes in the same places.

If you want to map the holes as well, you can use Array.from with its mapping callback:

let arr = [];
arr[1] = 2;
arr[7] = 10;
arr = Array.from(arr, x => x || null);

console.log(arr);

Unlike map, Array.from will go through all indexes of the array, including holes, passing undefined as x for the holes in the array to the mapping callback.

Another option is a simple for-of loop, because iteration visits holes in sparse arrays (which is why Array.from works above):

let arr = [];
arr[1] = 2;
arr[7] = 10;
const newArr = [];
for (const value of arr) {
    newArr.push(value || null);
}
arr = newArr;

console.log(arr);


Note that x || null will replace all falsy values with null (including 0 and "", which often trips people up). To just replace undefined, use x ?? null instead:

let arr = [];
arr[1] = 2;
arr[7] = 10;
arr = Array.from(arr, x => x ?? null);

console.log(arr);

or

let arr = [];
arr[1] = 2;
arr[7] = 10;
const newArr = [];
for (const value of arr) {
    newArr.push(value ?? null);
}
arr = newArr;

console.log(arr);

x ?? y (nullish coalescing) is like x || y but only uses y if x evaluates to undefined or null.

about 4 years ago · Juan Pablo Isaza Relatório

0

Try something very basic:

let arr = [];
arr[1] = 2; arr[7] = 10;
for(let i=0; i< arr.length; i++) {
    if(!arr[i]) arr[i]=null;
}
console.log(arr);

Output:

[
  null, 2,    null,
  null, null, null,
  null, 10
]
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