Getting rid of falsy values from arrays: the super simple guide

Getting rid of falsy values from arrays: the super simple guide

ยท

3 min read

Arrays are essential data structures used in JavaScript. It lets you store sequences of values. With array methods, you can transform and manipulate values in your arrays. Sometimes the data you get back from different data sources might not be consistent and can give you headaches when trying to access this data. In this simple guide, we look at how to get rid of falsy values from arrays.

The problem

In a perfect scenario, you would have total control of the data you need to use in your code. In reality that's not always the case. Often times you need to get data from a 3rd party API, a flat file, a database or a large dataset, and so on. Let's take a look at an example:

const allAccomodatingArray = [ {exist}, null, { anotherExist }, undefined, '' ]

The code snippet creates a variable and assigns the array. Observe the array contains some empty values. Most times we likely want to iterate through an array. Let's say we try to use a map on the array:

const newArray = allAccomodatingArray.map((el) => {
    console.log(el.prop) 
    // ๐Ÿšซ Cannot read property "prop" of null
})

This is expected as there are some empty values in the array. Accessing those values is not permitted as they are null and undefined. We can make checks for existence before accessing the elements.

const newArray = allAccomodatingArray.map((el) => {
    if (!el) return el;
    console.log(el.prop)
})

This solves the problem. But the empty values are still part of the new array. It kinda defeats the purpose because we'd be running around in circles.

An opinionated solution

We can filter the array by using Boolean() in the callback function to coerce each item to either true or false before passing it to map. This way, all values that are empty are filtered and we can safely access the items without error.

const newArray = allAccomodatingArray.filter((el) => Boolean(el)).map((el) => {
  console.log(el.item)
})

All good, eh? Though we can still write it in another way (see below). Objectively, depend on what you think is more readable.

const newArray = allAccomodatingArray.filter(Boolean).map((el) => {
  console.log(el.item)
})

Nothing fancy here, just the filter method passing each item as arg to Boolean. It then does the falsy checks and let map do the rest.

Conclusion

In this simple guide, we look at how to get rid of falsy values. Using a combination for in-built JavaScript object and some array method we were able to get rid of those falsy values. Having total control of our data sources might not be easy but we sure can prevent them from giving us headache.