In this freeCodeCamp algorithm we are tasked with removing all falsy values from an array. Oh yeah, and we will get to try our hand at the Array.filter() method!

Requirements

  • bouncer([7, "ate", "", false, 9]) should return [7, "ate", 9]
  • bouncer(["a", "b", "c"]) should return ["a", "b", "c"]
  • bouncer([false, null, 0, NaN, undefined, ""]) should return []
  • bouncer([1, null, NaN, 2, undefined]) should return [1, 2]

Real-World Use Cases

This is a useful and fairly straight-forward real-world algorithm that you could use in tons of places. The first thought that comes to mind is that it could be used to filter out votes for a proposal in which there's either a yes or a no, a true or false, or a 0 or 1. You could quickly and easily get all the results that are either true or false!

Psuedocode

// Create a function that accepts an array
    // Filter the array
        // Return truthy values

Solving the Algorithm

Setting up the function

Let's setup a function that accepts an array.

function bouncer(arr) {
    
};

Create the array filter & solve the algorithm

Here we get to take a look at the Array.filter() method which "returns a new array with all elements that pass the test implemented by the provided function".

With that said - we can just return all elements from the array, and the filter itself will return all methods that coerce to true aka "Truthy". A value will coerce to true so long as it is not considered false or "Falsy".

function bouncer(arr) {
  // Don't show a false ID to this bouncer.

	const truthy = arr.filter(item => {
		return item;
	});

  return truthy;
};
bouncer([7, "ate", "", false, 9])
// bouncer(["a", "b", "c"])
// bouncer([false, null, 0, NaN, undefined, ""])
// bouncer([1, null, NaN, 2, undefined])

Test this code in your browser console

Recap

In a fairly straighforward manner, we were able to use the Array.filter() to quickly sort through an array and return all "Truthy" values.

Shoot me an email at tim@timwheeler.com with any questions and if you enjoyed this, stay tuned and subscribe below! 👇