remove.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. var baseIteratee = require('./_baseIteratee'),
  2. basePullAt = require('./_basePullAt');
  3. /**
  4. * Removes all elements from `array` that `predicate` returns truthy for
  5. * and returns an array of the removed elements. The predicate is invoked
  6. * with three arguments: (value, index, array).
  7. *
  8. * **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull`
  9. * to pull elements from an array by value.
  10. *
  11. * @static
  12. * @memberOf _
  13. * @since 2.0.0
  14. * @category Array
  15. * @param {Array} array The array to modify.
  16. * @param {Array|Function|Object|string} [predicate=_.identity]
  17. * The function invoked per iteration.
  18. * @returns {Array} Returns the new array of removed elements.
  19. * @example
  20. *
  21. * var array = [1, 2, 3, 4];
  22. * var evens = _.remove(array, function(n) {
  23. * return n % 2 == 0;
  24. * });
  25. *
  26. * console.log(array);
  27. * // => [1, 3]
  28. *
  29. * console.log(evens);
  30. * // => [2, 4]
  31. */
  32. function remove(array, predicate) {
  33. var result = [];
  34. if (!(array && array.length)) {
  35. return result;
  36. }
  37. var index = -1,
  38. indexes = [],
  39. length = array.length;
  40. predicate = baseIteratee(predicate, 3);
  41. while (++index < length) {
  42. var value = array[index];
  43. if (predicate(value, index, array)) {
  44. result.push(value);
  45. indexes.push(index);
  46. }
  47. }
  48. basePullAt(array, indexes);
  49. return result;
  50. }
  51. module.exports = remove;