Search code examples
javascriptnode.jslodash

Filter an empty array from a parent array


How can I completely remove an empty array from a parent array, before adding a new element.

I have a structure that looks like this

var parentArray = [ ['123', '345'], [], ['12'] ]

I want to remove array at index 1 before adding a new array.

I have tried this but it doesn't remove it:

parentArray.filter((array, index) => {
    if (array.length === 0) {
        parentArray.splice(index, 1);
    }
})
parentArray.push(['435']);

console.log(parentArray);  //Still give  [["123", "345"], [], ["12"]]

Solution

  • You should not mutate your array in the filter method. The callback function should return true if you want to keep the item, false if not.

    const parentArray = [['123', '345'], [], ['12']];
    
    const filteredArray = parentArray.filter( item => item.length !== 0);
    
    console.log(filteredArray)