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