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