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

173
Visualizações
Remove empty arrays in array using jquery

I have 2 arrays - collections and settings. IN collections array I need to remove empty arrays but the same index I need to remove from array settings so I write:

$.each(collections, function(index, collection) {
        if (collection.length == 0) { 
          collections.splice(index, 1); 
          settings.splice(index, 1);
        }
    });

It works only for the first empty array but if there is more than 1 empty array I got error message:

Uncaught TypeError: Cannot read properties of undefined (reading 'length')

How to remove empty arrays from collections but at the same time to remove the same index from settings array?

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

0

Just do a truthy check before you access the length:

if (!collection || collections.length == 0) { ... }

(this will short-circuit if collection is falsy (undefined is falsy) and thus no error will be thrown).

I'm not sure what ramifications the modification of the array within $.each is having, but you could also just do this:

let collectionsCopy = collections;

$.each(collectionsCopy, function(index, collection) {
    if (!collection || collection.length == 0) { 
        collections.splice(index, 1); 
        settings.splice(index, 1);
    }
});

(i.e. create an array whose only purpose is to loop over collections with - massively inefficient but this will work and is not dissimilar from your original approach.)

To make a more effective solution you could also just store the indices you want removed:

let indices = [];

$.each(collections, function(index, collection) {
    if (!collection || collection.length == 0) {
        indices.push(index);
    }
});

$.each(indices, function(_, index) {
    collections.splice(index, 1);
    settings.splice(index, 1);
});

If you'd like to use filter:

collections = collections.filter((collection, index) => {
    if (!collection || collection.length == 0) {
        settings.splice(index, 1);
        return false;
    }
    return true;
});
about 4 years ago · Juan Pablo Isaza Relatório

0

Try this:

var collections = [
  [1],
  [],
  [],
  [2],
  []
];
var settings = [
  [5],
  [6],
  [7]
];

collections.forEach(function(collection, index) {
  if (collection.length === 0) {
    collections[index] = null;
    if (settings[index]) {
      settings[index] = null;
    }
  }
})

// then filter out the nulls
collections = collections.filter(function (v) { return v !== null });
settings = settings.filter(function (v) { return v !== null });

console.log('cols:', collections, 'setts:', settings); // cols:", [[1], [2]], "setts:", [[5], [8]]

fully working example is there: https://jsfiddle.net/5vfbdowL/1/

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