Files
Randell Dawson 1494a50123 fix(guide): restructure curriculum guide articles (#36501)
* fix: restructure certifications guide articles
* fix: added 3 dashes line before prob expl
* fix: added 3 dashes line before hints
* fix: added 3 dashes line before solutions
2019-07-24 13:29:27 +05:30

2.9 KiB

title
title
Falsy Bouncer

Falsy Bouncer


Problem Explanation

Remove all falsy values from an array.


Hints

Hint 1

Falsy is something which evaluates to FALSE. There are only six falsy values in JavaScript: undefined, null, NaN, 0, "" (empty string), and false of course.

Hint 2

We need to make sure we have all the falsy values to compare, we can know it, maybe with a function with all the falsy values...

Hint 3

Then we need to add a filter() with the falsy values function...


Solutions

Solution 1 (Click to Show/Hide)
function bouncer(arr) {
  let newArray = [];
  for (var i = 0; i < arr.length; i++) {
    if (arr[i]) newArray.push(arr[i]);
  }
  return newArray;
}

Code Explanation

  • We create a new empty array.
  • We use a for cycle to iterate over all elements of the provided array (arr).
  • We use the if statement to check if the current element is truthy or falsy.
  • If the element is truthy, we push it to the new array (newArray). This result in the new array (newArray) containing only truthy elements.
  • We return the new array (newArray).
Solution 2 (Click to Show/Hide)
function bouncer(arr) {
  return arr.filter(Boolean);
}

Code Explanation

  • The Array.prototype.filter method expects a function that returns a Boolean value which takes a single argument and returns true for truthy value or false for falsy value. Hence we pass the built-in Boolean function.