remove.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. var baseCallback = require('../internal/baseCallback'),
  2. basePullAt = require('../internal/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 bound to
  6. * `thisArg` and invoked with three arguments: (value, index, array).
  7. *
  8. * If a property name is provided for `predicate` the created `_.property`
  9. * style callback returns the property value of the given element.
  10. *
  11. * If a value is also provided for `thisArg` the created `_.matchesProperty`
  12. * style callback returns `true` for elements that have a matching property
  13. * value, else `false`.
  14. *
  15. * If an object is provided for `predicate` the created `_.matches` style
  16. * callback returns `true` for elements that have the properties of the given
  17. * object, else `false`.
  18. *
  19. * **Note:** Unlike `_.filter`, this method mutates `array`.
  20. *
  21. * @static
  22. * @memberOf _
  23. * @category Array
  24. * @param {Array} array The array to modify.
  25. * @param {Function|Object|string} [predicate=_.identity] The function invoked
  26. * per iteration.
  27. * @param {*} [thisArg] The `this` binding of `predicate`.
  28. * @returns {Array} Returns the new array of removed elements.
  29. * @example
  30. *
  31. * var array = [1, 2, 3, 4];
  32. * var evens = _.remove(array, function(n) {
  33. * return n % 2 == 0;
  34. * });
  35. *
  36. * console.log(array);
  37. * // => [1, 3]
  38. *
  39. * console.log(evens);
  40. * // => [2, 4]
  41. */
  42. function remove(array, predicate, thisArg) {
  43. var result = [];
  44. if (!(array && array.length)) {
  45. return result;
  46. }
  47. var index = -1,
  48. indexes = [],
  49. length = array.length;
  50. predicate = baseCallback(predicate, thisArg, 3);
  51. while (++index < length) {
  52. var value = array[index];
  53. if (predicate(value, index, array)) {
  54. result.push(value);
  55. indexes.push(index);
  56. }
  57. }
  58. basePullAt(array, indexes);
  59. return result;
  60. }
  61. module.exports = remove;