Back to main page Traveling Coderman

Best of Lodash

Lodash has a lot of functions.

Some are now present natively and some are not that useful on a regular basis.

Here, I have put together a couple of helpful functions for working with collections and objects that I use on a regular basis.

Example data definitions 🔗

const what = {
label: "What?",
section: "General",
answer: "Yes",
};
const where = {
label: "Where?",
section: "General",
answer: "No",
};
const when = {
label: "When?",
section: "Time",
answer: "Maybe",
};
const which = {
label: "Which?",
section: undefined,
answer: "Yes",
};

Helpful functions with example 🔗

toPairs({ "What?": what, "Where?": where });
// => [['What?', what], ['Where?', where]]

fromPairs([
["What?", what],
["Where?", where],
]);
// => { 'What?': what, 'Where?': where }

mapKeys((label) => label.toUpperCase(), { "What?": what, "Where?": where });
// => { 'WHAT?': what, 'WHERE?': where }

mapValues(
(question) => ({ ...question, section: question.section ?? "Other" }),
{ "What?": what, "Which?": which }
);
// => { 'What?': what, 'Which?': { label: 'Which?', section: 'Other', answer: 'Yes' } }

omit(["section"], what);
// => { label: 'What?', answer: 'Yes' }

pick(["label", "answer"], what);
// => { label: 'What?', answer: 'Yes' }

differenceBy((question) => question.label, [what, where, which], [which]);
// => [what, where]

intersectionBy(
(question) => question.label,
[what, where, which],
[what, when]
);
// => [what]

unionBy((question) => question.label, [what, where], [what, when]);
// => [what, where, when]

uniqBy((question) => question.label, [what, where, what]);
// => [what, where]

sortBy((question) => question.label, [what, where, when, which]);
// => [what, when, where, which]

groupBy((question) => question.section ?? "Other", [what, where, when, which]);
// => { General: [what, where], Time: [when], Other: [which] }

partition((question) => question.answer === "Yes", [what, where, when, which]);
// => [[what, which], [where, when]]

dropRight(2, [what, where, when, which]);
// => [what, where]

last([what, where, when, which]);
// => which