Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

remove.js 1.3KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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 {Function} [predicate=_.identity] The function invoked per iteration.
  17. * @returns {Array} Returns the new array of removed elements.
  18. * @example
  19. *
  20. * var array = [1, 2, 3, 4];
  21. * var evens = _.remove(array, function(n) {
  22. * return n % 2 == 0;
  23. * });
  24. *
  25. * console.log(array);
  26. * // => [1, 3]
  27. *
  28. * console.log(evens);
  29. * // => [2, 4]
  30. */
  31. function remove(array, predicate) {
  32. var result = [];
  33. if (!(array && array.length)) {
  34. return result;
  35. }
  36. var index = -1,
  37. indexes = [],
  38. length = array.length;
  39. predicate = baseIteratee(predicate, 3);
  40. while (++index < length) {
  41. var value = array[index];
  42. if (predicate(value, index, array)) {
  43. result.push(value);
  44. indexes.push(index);
  45. }
  46. }
  47. basePullAt(array, indexes);
  48. return result;
  49. }
  50. module.exports = remove;