Traverse array and take empty widgets

Asked

Viewed 1,006 times

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 white elements.

  • Can you define for us what you consider "empty" in this context? A common white space is not considered empty. What are the cases that you will consider empty? Spaces? Line breaks? Tabs? Not visible characters? etc.

  • @Andersoncarloswoss spaces/blank.

  • Why did the indices not drop in the result ? They should not be 0.1 and 2 ? The same in relation to the length, because it is 5 and not 3 ?

  • @Isac I just erased the lines to show how I’d like it to be an example, it’s the same from above.

  • And the other characters, line break, tab, etc, will be considered "empty" too? Example: {tag: '\t\r\n'}

1 answer

5

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

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 make a normal loop/loop with a for for example and go testing with a if and adding to a new array if it is not empty, but ends up representing the same logic as the filter already follows.

As commented by @fernandosavio on filter true return to keep the element or false to delete. As a string empty is a falsy value, and a string with content is a Truthy value can use the string coming out of trim directly:

const filtrado = arr.filter(x => x.tag.trim());
  • 1

    +1 For the record, the .length > 0 is unnecessary in the function of filter as an empty string, when converted to boolean, is false. Could be x => x.tag.trim() no problem.

  • @fernandosavio I appreciate the comment. Yes indeed it is something that is usually used in this type of cases that I ended up not even mention, but that is relevant.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.