Hone logo
Hone
Problems

Compact Array: Remove Falsy Values

This challenge asks you to implement a function that takes an array and returns a new array with all "falsy" values removed. Falsy values are those that evaluate to false in a boolean context, such as false, null, 0, "" (empty string), undefined, and NaN. This is a common operation in JavaScript for cleaning up data.

Problem Description

You need to write a JavaScript function called compactArray that accepts a single argument: an array. This function should process the input array and return a new array containing only the "truthy" values from the original array. The order of the truthy values should be preserved.

Key Requirements:

  • The function must return a new array; it should not modify the original array.
  • All falsy values must be excluded from the returned array.
  • The relative order of the truthy values must be the same as in the original array.

Falsy values in JavaScript include:

  • false
  • null
  • 0 (the number zero)
  • "" (an empty string)
  • undefined
  • NaN (Not a Number)

All other values are considered truthy.

Examples

Example 1:

Input: [0, 1, false, 2, "", 3, null, "hello", undefined, NaN, 4]
Output: [1, 2, 3, "hello", 4]
Explanation: The falsy values (0, false, "", null, undefined, NaN) have been removed, leaving only the truthy values in their original order.

Example 2:

Input: ["apple", "banana", "cherry"]
Output: ["apple", "banana", "cherry"]
Explanation: All values in the input array are truthy, so the output array is identical to the input array.

Example 3:

Input: [undefined, null, NaN, 0, ""]
Output: []
Explanation: All values in the input array are falsy, so the returned array is empty.

Constraints

  • The input will always be an array.
  • The array can contain any type of JavaScript values.
  • The input array can be empty.
  • The solution should be reasonably efficient, aiming for a time complexity of O(n) where n is the number of elements in the input array.

Notes

  • Consider using built-in JavaScript array methods or simple iteration to achieve this.
  • Remember that JavaScript has a convenient way to evaluate values in a boolean context.
Loading editor...
javascript