2

Is there a way to filter an array of objects to retrieve an array of the values I need but also remove the filtered values from the original list. Something like this

let array = [1, 2, 3, 4, 5];
const filteredList, listContainingRemainingValues = array.filter(value => value > 3);

Output:

filteredList = [4, 5];
listContainingRemainingValues = [1, 2, 3];

Is there any built in functionality to do this already in Javascript or will i have to roll my own?

Steve Fitzsimons
  • 3,754
  • 7
  • 27
  • 66

5 Answers5

1

You could take an array as temporary storage for the wanted result.

const
    array = [1, 2, 3, 4, 5],
    [remaining, filtered] = array.reduce((r, v) => (r[+(v > 3)].push(v), r), [[], []]);

console.log(filtered);
console.log(remaining);

Same with lodash's _.partition

const
    array = [1, 2, 3, 4, 5],
    [filtered, remaining] = _.partition(array, v => v > 3);

console.log(filtered);
console.log(remaining);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

Sort the array, find the index of your threshold value and then splice it in order to remove the elements from the input array and to return the removed elements:

const array = [1, 2, 3, 4, 5];
// just if the input array is not already sorted
array.sort();
const removedElements = removeAndGet(array, 3);
console.log('input array:', array);
console.log('removed elements:', removedElements)

function removeAndGet(input, thresholdValue) {
  const ind = input.findIndex(a => a > thresholdValue);
  return ind > -1 ? input.splice(ind) : [];
}
quirimmo
  • 9,800
  • 3
  • 30
  • 45
0

Here's one option:

const array = [1, 2, 3, 4, 5];

// Get all the indices we want to keep:
const matchingIndices = array
        .map((v, i) => [i, v > 3])
        .filter((el) => el[1])
        .map((el) => el[0]);

// Filter the input array by indices we want/don't want
const matching = array.filter((v, i) => matchingIndices.indexOf(i) >= 0);
const nonMatching = array.filter((v, i) => matchingIndices.indexOf(i) < 0);
Mark Ormesher
  • 2,289
  • 3
  • 27
  • 35
0

Use 2 filters

let array = [1, 2, 3, 4, 5];
let filteredList = array.filter(value => value > 3);
let listContainingRemainingValues = array.filter(f => !filteredList.includes(f))
console.log(filteredList)
console.log(listContainingRemainingValues)
holydragon
  • 6,158
  • 6
  • 39
  • 62
0

Here's one of the way using underscore library:

var data = [1, 2, 3, 4, 5]

var x = _.reject(data, function(num){ return num > 3; });
var y = _.difference(data, x);

console.log(x);
console.log(y);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>
Prerak Sola
  • 9,517
  • 7
  • 36
  • 67