0

I'm trying to find whether lodash has a function where I can filter based on some query, return an array of the matched objects, but remove the matched objects from the original array.

So very similar to _.filter, but where the original array is modified with the matched elements removed.

Example

var originalArray = [1, 2, 3, 4, 5];
console.log(originalArray);
----> 1, 2, 3, 4, 5

var evenNumbers = _.somethingSimilarToFilter(originalArray, function(n) {
    return n % 2 === 0
});

console.log(evenNumbers);
----> 2, 4

console.log(originalArray);
----> 1, 3, 5

1 Answer 1

1

You can done it using native JavaScript Array#filter and Array#splice methods

var originalArray = [1, 2, 3, 4, 5];
var evenNumbers = originalArray.filter(function(n, i, arr) {
  // just remove the element from array if  even number
  return n % 2 === 0 && arr.splice(i, 1)
});

console.log(originalArray, evenNumbers);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.