[Medium] LeetCode JS 30 - 2705. Compact Object

March 7, 2024

☕️ Support Us
Your support will help us to continue to provide quality content.👉 Buy Me a Coffee

LeetCode 30 Days of JavaScript

This question is from LeetCode's 30 Days of JavaScript Challenge

2705. Compact Object

Question Prompt

Let's say you're tasked with cleaning up an array by removing any falsey values. Can you walk through how you'd implement a function called compact(array) that achieves this? Keep in mind that falsey values in this context include false, null, 0, empty strings, undefined, and NaN.

compact([0, 1, false, 2, "", 3, "hello"]); // [1, 2, 3, 'hello']
compact([null, undefined, NaN, " "]); // [' ']
compact([{ name: "Alice" }, null, { age: 30 }, undefined]); // [{ name: 'Alice' }, { age: 30 }]

Solutions

Looking to practice more questions like these? We recommend GreatFrontEnd, the best platform for honing your frontend interview skills!

  • Starts by creating an empty array called result. This array will eventually hold the compacted elements.
  • The for...of loop steps through each value in the original array.
  • The if (value) conditional statement is crucial. It leverages JavaScript's concept of truthy and falsy values.
    • Truthy values, like non-zero numbers, non-empty strings, and objects, will pass this check.
    • Falsy values, like falsenull0, empty strings, undefined, and NaN, will fail and be excluded from the result.
  • If a value passes the truthiness check, it's added to the result array using the result.push(value) method.
  • Once the loop completes, the function returns the result array, which now contains only the truthy values from the original input array.
function compact(array) {
  const result = [];
  for (const value of array) {
    if (value) {
      result.push(value);
    }
  }
  return result;
}

Or we can take a more concise approach to compacting the array, utilizing the built-in filter method in JavaScript.

  • The array.filter(Boolean) call applies the filter method directly to the input array.
  • The Boolean function is passed as a predicate to filter. This function acts as a decision-maker for each element.
  • For each element in the array, Boolean is implicitly called on it. Truthy values return true, while falsy values return false.
  • The filter method constructs a new array, including only those elements for which the predicate (in this case, Boolean) returned true.
  • The function directly returns this new, filtered array, containing only the truthy elements from the original input.
function compact(array) {
  return array.filter(Boolean);
}
☕️ Support Us
Your support will help us to continue to provide quality content.👉 Buy Me a Coffee