0

I want to delete null elements in my array

 [ [ null, [ [Array], [Array] ] ] ]

The desired structure is [ [[Array],[Array]], [[Array],[Array]], [[Array],[Array]] ]

if any of the objects are undefined/null such as :

[ [[Array],[]],  [[Array],[Array]],  [[Array],[Array]] ]

I wish to remove the full element [[Array],[]]

The 'yes' and 'no' are correctly identifying which elements have the undefined. So I know this code is functioning properly. I tried assigning the empty array as null and then filtering by adding to new array if != null but it did not work.

var filter = Total[0][i];

filter.forEach(e => {
    if ((e[0] !== undefined)&&(e[1] !== undefined)) {
        console.log('yes');
    } else {
        console.log('no');
        Total[0][i] = null;
    }
});

var totalArray = [];

const resultFilter = Total.filter(arr => arr != null);

var Filtereddata = resultFilter.filter(function(element) {
    return element !== null;
}

I am unsure how to remove the element or filter into a new array without null. The null Array is causing problems client side with extra , it would be better to remove the index/element altogether.

2
  • 2
    An empty array is not undefined or null Commented Apr 10, 2019 at 16:54
  • 3
    Please update the question with code creating example input, and with examples of the output you want. Commented Apr 10, 2019 at 16:55

1 Answer 1

2

You could just recursively filter out nulls:

 const noNull = array => array
    .map(el => Array.isArray(el) ? noNull(el) : el)
    .filter(it => it !== null);

If you also want to remove empty arrays, you can replace [] with null:

 const noEmpty = array => array.length ? array : null;

Then change the recursive call from noNull(el) to noEmpty(noNull(el))

Sign up to request clarification or add additional context in comments.

2 Comments

Fabulous, thank you very much! this worked for me! :)
@annaM glad to help :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.