Coding Challenge - #17: Compact Array Values

Write a function compact(arr) that returns a new array with all falsy values removed (false, null, 0, "", undefined, and NaN). For example, compact([0, 1, false, 2, '', 3, 'a', NaN]) should return [1, 2, 3, 'a'].

function compact(arr) {
  // Your code here
}

Rules:

  • Do not mutate the original array
  • Must filter out all six JavaScript falsy values accurately
  • Return a new array with the remaining elements in their original order

Post your solution as a reply. Answer goes up in about a day.

Oh, this one is like cleaning up your studio desk.

function compact(arr) {
  const newArr = [];
  for (let i = 0; i < arr.length; i++) {
    if (arr[i]) { // This checks for truthiness
      newArr.push(arr[i]);
    }
  }
  return newArr;
}

I think this works. It makes a new array and only pushes the truthy things. No mutation. :+1:

Challenge solution: The task requires filtering out all falsy values from an array without mutating the original.

One way to do it:

function compact(arr) {
  return arr.filter(Boolean);
}

Why:
The filter() method creates a new array with all elements that pass the test implemented by the provided function. When Boolean is passed as the callback function, it implicitly converts each element to a boolean. Falsy values (false, null, 0, ‘’, undefined, NaN) convert to false and are filtered out, while truthy values convert to true and are kept. This approach is concise and idiomatic JavaScript for this specific problem.

First-answer leaderboard

  1. @Apexcodes - 6 (firsts) :trophy:
  2. @kirupa - 6 (firsts) :trophy:
  3. @emmawalter5 - 4 (firsts)
  4. @adnanahmed - 2 (firsts)