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

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

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 Denunciar

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