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?
2 Answers 2
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 } ]
-
3\$\begingroup\$ I would prefer to use the
includes
function._.filter(users, v => !_.includes(excludeProjects, v.project))
\$\endgroup\$Gerrit0– Gerrit02017年10月27日 21:58:16 +00:00Commented Oct 27, 2017 at 21:58 -
\$\begingroup\$ Hey thanks for suggestion
_.includes
didnt occur to my mind then. \$\endgroup\$Muhammad Faizan– Muhammad Faizan2017年10月28日 07:42:57 +00:00Commented Oct 28, 2017 at 7:42 -
\$\begingroup\$ no need for lodash, ES6:
users.filter(v => !_.includes(excludeProjects, v.project))
\$\endgroup\$younes0– younes02018年05月31日 15:13:56 +00:00Commented May 31, 2018 at 15:13 -
\$\begingroup\$ I would have answered it with ES6, but it could be his requirement to use
lodash
\$\endgroup\$Muhammad Faizan– Muhammad Faizan2018年06月01日 09:43:12 +00:00Commented Jun 1, 2018 at 9:43
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>
users.filter(user => !excludeProjects.includes(user.project))
\$\endgroup\$