Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

179
Views
Eliminar matrices vacías en una matriz usando jquery

Tengo 2 matrices: collections y settings . En la matriz de collections , necesito eliminar las matrices vacías, pero el mismo índice que necesito eliminar de la configuración de la matriz, así que escribo:

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

Funciona solo para la primera matriz vacía, pero si hay más de 1 matriz vacía, recibí un mensaje de error:

TypeError no capturado: no se pueden leer las propiedades de undefined (leyendo 'longitud')

¿Cómo eliminar matrices vacías de collections pero al mismo tiempo eliminar el mismo índice de la matriz de settings ?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Simplemente haga una verificación veraz antes de acceder a la longitud:

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

(Esto provocará un cortocircuito si collection es falsa ( undefined es falso) y, por lo tanto, no se generará ningún error).

No estoy seguro de qué ramificaciones tiene la modificación de la matriz dentro $.each , pero también podría hacer esto:

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

(es decir, cree una matriz cuyo único propósito sea recorrer las collections con - masivamente ineficiente, pero esto funcionará y no es diferente de su enfoque original).

Para hacer una solución más efectiva, también puede almacenar los índices que desea eliminar:

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

Si desea utilizar el 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 Report

0

Prueba esto:

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

ejemplo completamente funcional está ahí: https://jsfiddle.net/5vfbdowL/1/

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!