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());
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.
– Woss
@Andersoncarloswoss spaces/blank.
– user130725
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
@Isac I just erased the lines to show how I’d like it to be an example, it’s the same from above.
– user130725
And the other characters, line break, tab, etc, will be considered "empty" too? Example:
{tag: '\t\r\n'}
– Woss