JAVASCRIPT   5

compact.js

Guest on 11th June 2021 03:42:37 AM

  1. /**
  2.  * Creates an array with all falsey values removed. The values `false`, `null`,
  3.  * `0`, `""`, `undefined`, and `NaN` are falsey.
  4.  *
  5.  * @static
  6.  * @memberOf _
  7.  * @category Array
  8.  * @param {Array} array The array to compact.
  9.  * @returns {Array} Returns the new array of filtered values.
  10.  * @example
  11.  *
  12.  * _.compact([0, 1, false, 2, '', 3]);
  13.  * // => [1, 2, 3]
  14.  */
  15. function compact(array) {
  16.   var index = -1,
  17.       length = array ? array.length : 0,
  18.       resIndex = -1,
  19.       result = [];
  20.  
  21.   while (++index < length) {
  22.     var value = array[index];
  23.     if (value) {
  24.       result[++resIndex] = value;
  25.     }
  26.   }
  27.   return result;
  28. }
  29.  
  30. module.exports = compact;

Raw Paste


Login or Register to edit or fork this paste. It's free.