Basic approach
forEach
Basically for any kind of operation with array, you can use a forEach.In this case you just create as much help variables as you neeed and process filter logic in forEach.
const males = []
const females = []
users.forEach(u=> u.gender === 'm' ? males.push(u) : females.push(u))
Another javascript Loop
Another simple solution is to use one of javascript loops, in my example I have chosen for-in but principle is the same as in forEach example
const males = []
const females = []
for (u in users) {
if (u.gender === 'm') {
males.push(u)
} else {
females.push(u)
}
}
Advanced approach
reduce
Reduce is function which allows as to process array loop and store result to single variable called accumulator, which is shared in every loop step. We can use [[],[]] => array of arrays accumulator
const [males, females] = users.reduce((acc, user) => {
if (user.gender === 'm') {
acc[0].push(u)
} else {
acc[1].push(u)
}
return acc;
}, [[], []])
reduce one-liner
Same principle as the last, but refactored to one line. (not the beast readability)
const [males, females] = users.reduce((acc, u) => (u.gender === 'm' ? acc[0].push(u) : acc[1].push(u), acc), [[],[]])
lodash/underscore
If you use lodash, you can use a groupBy function, which create object with keys consist of filter attributes and array values, same function you can find also in underscore.
const result = _.groupBy(users, 'gender'));
// { 'm': [{male1, male2}], 'f': [female1, female2] }