How to remove false, null, 0, “”, undefined, NaN from array in JavaScript?

Total
0
Shares

Use _.compact(array) of Lodash to remove all false values like – false, null, 0, “”, undefined and NaN from array in JavaScript and ReactJS.

Suppose you have an array with mixed values, like this –

// Array with false values 👇
arr = ["a", 1, false, 3, undefined, "ironman", "", "", Math.sqrt(-1, 2)]

You can see that the array has false, undefined, empty values and NaN (Math.sqrt(-1, 2) square root of negative number is not real).

The desired filtered array should look like this –

arr = ["a", 1, 3, "ironman"]

The Lodash function _.compact(array) accepts only the array as parameter.

Code Example

1. Using JavaScript & Lodash

arr = ["a", 1, false, 3, undefined, "ironman", "", "", Math.sqrt(-1, 2)]

console.log(_.compact(arr))

// Output 👉 ["a", 1, 3, "ironman"]

2. Using ReactJS & Lodash

import _ from "lodash";

export default function App() {
  const arr = ["a", 1, false, 3, undefined, "ironman", "", "", Math.sqrt(-1, 2)];

  return <pre>{JSON.stringify(_.compact(arr), null, "\t")}</pre>;
}

// Output 👇
/*
[
	"a",
	1,
	3,
	"ironman"
]
*/

Live Demo

Open Live Demo