Hone logo
Hone
Problems

Compact Array in JavaScript

This challenge focuses on creating a function that removes all falsy values from an array. Falsy values in JavaScript are false, null, undefined, 0, "" (empty string), and NaN. This is a common utility function used for data cleaning and preparing data for further processing, ensuring you're working with only meaningful values.

Problem Description

You are tasked with writing a JavaScript function called compact that takes an array as input and returns a new array containing only the truthy values from the original array. The original array can contain any data type, including numbers, strings, booleans, objects, and other arrays. The function should not modify the original array; it should return a new array.

Key Requirements:

  • The function must iterate through the input array.
  • For each element, it must determine if the element is truthy or falsy.
  • If an element is truthy, it must be added to the new array.
  • If an element is falsy, it must be skipped.
  • The function must return the new array containing only truthy values.

Expected Behavior:

The function should handle various data types and edge cases correctly. It should return an empty array if the input array is empty or contains only falsy values.

Edge Cases to Consider:

  • Empty input array.
  • Array containing only falsy values.
  • Array containing a mix of truthy and falsy values of different types.
  • Array containing nested arrays (these should be treated as truthy if not empty, falsy if empty).
  • Array containing objects (non-empty objects are truthy).

Examples

Example 1:

Input: [0, 1, false, 2, "", 3]
Output: [1, 2, 3]
Explanation: The falsy values (0, false, "") are removed, and the truthy values (1, 2, 3) are included in the new array.

Example 2:

Input: [1, "a", true, [1,2], {a:1}]
Output: [1, "a", true, [1,2], {a:1}]
Explanation: All elements are truthy, so the new array is identical to the original.

Example 3:

Input: [false, null, undefined, NaN, 0]
Output: []
Explanation: All elements are falsy, so the new array is empty.

Example 4:

Input: []
Output: []
Explanation: The input array is empty, so the new array is also empty.

Constraints

  • The input array can contain any data type.
  • The function must not modify the original array.
  • The function must return a new array.
  • The time complexity should be O(n), where n is the length of the input array.
  • The space complexity should be O(n) in the worst case (when all elements are truthy).

Notes

Consider using a for loop or the filter method to iterate through the array. The filter method provides a concise way to create a new array based on a condition. Remember that in JavaScript, any value that is not explicitly true is considered falsy. Think about how you can leverage JavaScript's truthy/falsy nature to efficiently solve this problem.

Loading editor...
javascript