Go through array and draw empty elements

1

I have this array:

{data: Array(5)}
data: Array(5)
0: {tag: " "}
1: {tag: "a"}
2: {tag: "b"}
3: {tag: "c"}
4: {tag: "  "}
length: 5

How do I go through the array and take out the empty elements?

ex:

{data: Array(5)}
    data: Array(5)
    1: {tag: "a"}
    2: {tag: "b"}
    3: {tag: "c"}
    length: 5

"Empty" would be elements in whites.

    
asked by anonymous 09.11.2018 / 16:21

1 answer

5

You can use filter that returns you a filtered array according to the criteria you want. In case it is enough that the criterion is applied with the trim to cut the blanks and guarantee at least one task:

const arr = [{tag:" "}, {tag:"a"}, {tag:"b"}, {tag:"c"}, {tag:"  "}];

const filtrado = arr.filter(x => x.tag.trim().length > 0);
console.log(filtrado);

Of course, you can also do a loop / normal loop with for for example and go testing with a if and add to a new array if it is not empty, but ends up representing the same logic as filter already follows.

As commented by @fernandosavio in filter it is worth returning true to keep element or false to delete. As an empty%% is a falsy value , and one string with content is a truthy value you can use the string that exits from string directly:

const filtrado = arr.filter(x => x.tag.trim());
    
09.11.2018 / 16:38