10
\$\begingroup\$

I ran into a scenario, I'll simplify the data to user/project, where I needed to take values like:

users: [
  {name: 'bob', project: 1},
  {name: 'sam', project: 2},
  {name: 'ted', project: 3},
];

and given an array of project ids I wish to exclude such as

excludeProjects: [1,3];

I want to return [{name: 'sam', project: 2}];

I was able to do this with a custom filter function:

let usersNotInProject = _.filter(users, function(o) { 
    for (var i=0; i<excludeProjects.length; i++){
        if (excludeProjects[i]===o.project){
            return false;
        }
    }
    return true;
});

However, I believe I am missing some more elegant way to do this with lodash. Is a custom function really needed for this scenario?

\$\endgroup\$
2
  • 2
    \$\begingroup\$ Without lodash: users.filter(user => !excludeProjects.includes(user.project)) \$\endgroup\$
    – Tushar
    Oct 26 '17 at 5:16
  • \$\begingroup\$ I would have given the same suggestion, but since the purpose was a "lodash" solution, i remained with lodash :) \$\endgroup\$ Oct 26 '17 at 12:34
15
\$\begingroup\$

You can do it with filter:

let users = [
  {name: 'bob', project: 1},
  {name: 'sam', project: 2},
  {name: 'ted', project: 3},
];
let excludeProjects = [1,3];
_.filter(users, (v) => _.indexOf(excludeProjects, v.project) === -1) // assign it to some variable
// Returns [ { name: 'sam', project: 2 } ]

OR other way of doing it is suggested in comments, this is more elegant:

_.filter(users, (v) => !_.includes(excludeProjects, v.project));
// Returns [ { name: 'sam', project: 2 } ]
\$\endgroup\$
4
  • 3
    \$\begingroup\$ I would prefer to use the includes function. _.filter(users, v => !_.includes(excludeProjects, v.project)) \$\endgroup\$
    – Gerrit0
    Oct 27 '17 at 21:58
  • \$\begingroup\$ Hey thanks for suggestion _.includes didnt occur to my mind then. \$\endgroup\$ Oct 28 '17 at 7:42
  • \$\begingroup\$ no need for lodash, ES6: users.filter(v => !_.includes(excludeProjects, v.project)) \$\endgroup\$
    – younes0
    May 31 '18 at 15:13
  • \$\begingroup\$ I would have answered it with ES6, but it could be his requirement to use lodash \$\endgroup\$ Jun 1 '18 at 9:43
2
\$\begingroup\$

Use _.differenceWith() to exclude the items:

const users = [
  {name: 'bob', project: 1},
  {name: 'sam', project: 2},
  {name: 'ted', project: 3},
];
const excludeProjects = [1,3];

const result = _.differenceWith(users, excludeProjects, 
  ({ project }, id) => project === id
);

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.