Languages
[Edit]
EN

TypeScript - remove empty elements from array

0 points
Created by:
Vanessa-Drake
718

In this article, we would like to show you how to remove empty elements from an array in TypeScript.

Quick solution:

const outputArray: type[] = inputArray.filter(x => x);

 

Alternative solutions

When we want to keep zeros too:

const outputArray: type[] = inputArray.filter(x => x || x === 0);

When we want to keep empty strings too:

const outputArray: type[] = inputArray.filter(x => x || x === '');

 

Practical example

In this example, we use filter() method to create a copy of the values array without empty elements.

const values: unknown[] = ['A', 'B', 1, -2, 0, null, undefined, , , , '', '', 'C', 'D'];
const result: unknown[] = values.filter((x) => x);

console.log(result);

Output:

[ 'A', 'B', 1, -2, 'C', 'D' ]

See also

  1. JavaScript - remove empty elements from array

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join