compact.js 658 B

123456789101112131415161718192021222324252627282930
  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. while (++index < length) {
  21. var value = array[index];
  22. if (value) {
  23. result[++resIndex] = value;
  24. }
  25. }
  26. return result;
  27. }
  28. module.exports = compact;