There was a time when installing Lodash was almost an automatic decision when starting a JavaScript project.
Need to group an array of objects? Lodash.
Need to remove duplicate values? Lodash.
Need to access a deeply nested property without crashing your application? Lodash again.
It solved many of the inconveniences of working with JavaScript, giving developers a consistent collection of useful, well-tested functions.
But JavaScript has changed considerably over the years.
Some of the utility functions we used to install an entire library for are now available natively. Others can be replaced with a single line of readable JavaScript.
This doesn't mean Lodash is obsolete. It still provides functionality that JavaScript doesn't offer directly, and replacing a perfectly good implementation just to remove a dependency isn't always worth the effort.
However, if you're starting a new project or reviewing an existing one, here are five things you might no longer need Lodash for.
1. Removing duplicate values with Set
Removing duplicates from an array is one of those tasks that appears surprisingly often in everyday development.
Perhaps you're combining product categories from multiple API responses, collecting unique email addresses, or preparing a list of tags for a search filter.
With Lodash, we might write:
import { uniq } from "lodash-es";
const categories = [
"JavaScript",
"TypeScript",
"React",
"JavaScript",
"React"
];
const uniqueCategories = uniq(categories);
Modern JavaScript already provides a data structure designed specifically for storing unique values: Set.
const uniqueCategories = [...new Set(categories)];
console.log(uniqueCategories);
// ["JavaScript", "TypeScript", "React"]
A Set stores unique values and preserves their insertion order. The spread operator converts the resulting collection back into an array.
There is no additional dependency, and the intention of the code is reasonably clear.
What about duplicate objects?
This is where things become slightly more interesting.
const users = [
{ id: 1, name: "Alex" },
{ id: 2, name: "Sarah" },
{ id: 1, name: "Alex" }
];
const uniqueUsers = [...new Set(users)];
console.log(uniqueUsers.length);
// 3
Why three instead of two?
JavaScript compares objects by reference when determining uniqueness in a Set. Even though two objects contain identical properties, they are still separate objects.
Lodash handles property-based deduplication with uniqBy().
const uniqueUsers = _.uniqBy(users, "id");
We can achieve similar behaviour using a combination of Set and filter().
const seen = new Set();
const uniqueUsers = users.filter(user => {
if (seen.has(user.id)) {
return false;
}
seen.add(user.id);
return true;
});
console.log(uniqueUsers);
// [
// { id: 1, name: "Alex" },
// { id: 2, name: "Sarah" }
// ]
This retains the first occurrence of each user ID.
You might also encounter this shorter alternative:
const uniqueUsers = [
...new Map(users.map(user => [user.id, user])).values()
];
Be careful, though. The Map approach retains the last object associated with each ID, whereas Lodash's uniqBy()retains the first.
That distinction can matter when two records contain different information.
For simple arrays of strings or numbers, Set is usually all you need. For more complicated deduplication requirements, Lodash may still be the more readable option.
2. Accessing nested properties with optional chaining
Anyone who has worked with REST APIs knows how unpredictable deeply nested objects can be.
Consider the following response:
const user = {
id: 101,
name: "Alex",
profile: {
address: {
city: "Singapore"
}
}
};
Accessing the city seems straightforward.
const city = user.profile.address.city;
But what happens when a user hasn't completed their profile?
const user = {
id: 102,
name: "Sarah",
profile: null
};
Our application throws an error.
For years, Lodash's get() function provided a convenient solution.
const city = _.get(
user,
"profile.address.city",
"Unknown"
);
Instead of throwing an error when an intermediate property is missing, Lodash returns the supplied default value when the resolved value is undefined.
Since ES2020, JavaScript has provided an elegant native alternative.
const city =
user.profile?.address?.city ?? "Unknown";
We can safely access nested properties using optional chaining (?.) and provide a fallback using nullish coalescing (??).
These operators also work nicely with arrays.
const firstProduct = order?.items?.[0]?.name;
And optional function calls.
settings.onSave?.();
For TypeScript developers, there's another advantage.
Consider the difference between:
_.get(user, "profile.adress.city");
And:
user.profile?.adress?.city;
Notice the misspelling of address.
With a properly typed object, the second version allows TypeScript to check each property directly. You also benefit from property autocomplete and editor-assisted refactoring.
Some Lodash type definitions can infer valid paths, but ordinary property access remains more straightforward for statically known object structures.
One difference worth remembering
Optional chaining and nullish coalescing are not exact replacements for every use of _.get().
Consider this object:
const settings = {
theme: null
};
These two expressions produce different results:
_.get(settings, "theme", "light");
// null
settings.theme ?? "light";
// "light"
Lodash's default value is used when the resolved value is undefined, whereas ?? also treats null as a reason to use the fallback.
Lodash is also useful when property paths are dynamically generated strings.
For ordinary property access, however, optional chaining is usually the simpler choice.
3. Grouping arrays with Object.groupBy()
Grouping data is something we do regularly, whether we're building dashboards, generating reports, or organising products into categories.
Suppose we're building a simple expense tracking application.
const expenses = [
{ name: "Lunch", category: "Food", amount: 12 },
{ name: "Taxi", category: "Transport", amount: 25 },
{ name: "Coffee", category: "Food", amount: 6 },
{ name: "Internet", category: "Utilities", amount: 49 }
];
We want to display expenses grouped by category.
Lodash makes this particularly easy.
const grouped = _.groupBy(expenses, "category");
Before ES2024, replacing this with native JavaScript often meant writing something like this:
const grouped = expenses.reduce((result, expense) => {
const category = expense.category;
if (!result[category]) {
result[category] = [];
}
result[category].push(expense);
return result;
}, Object.create(null));
It works, but it's considerably more verbose than the Lodash equivalent.
Fortunately, we no longer need to write that implementation ourselves.
JavaScript now has Object.groupBy().
const grouped = Object.groupBy(
expenses,
expense => expense.category
);
The result contains the following groups:
{
Food: [
{ name: "Lunch", category: "Food", amount: 12 },
{ name: "Coffee", category: "Food", amount: 6 }
],
Transport: [
{ name: "Taxi", category: "Transport", amount: 25 }
],
Utilities: [
{ name: "Internet", category: "Utilities", amount: 49 }
]
}
What makes this particularly useful is that we aren't limited to grouping by existing properties.
We can group elements according to any condition.
const grouped = Object.groupBy(expenses, expense =>
expense.amount >= 20 ? "expensive" : "affordable"
);
Or group orders according to their delivery status.
const grouped = Object.groupBy(orders, order =>
order.deliveredAt ? "delivered" : "pending"
);
The callback determines which group each element belongs to.
What about Map.groupBy()?
JavaScript also introduced Map.groupBy().
The main difference is that Object.groupBy() uses property keys, while Map.groupBy() allows arbitrary values, including objects, to serve as keys.
Here's a situation where that becomes useful.
const orders = [
{ id: 1, paid: true },
{ id: 2, paid: false },
{ id: 3, paid: true }
];
const grouped = Map.groupBy(
orders,
order => order.paid
);
console.log(grouped.get(true));
// [
// { id: 1, paid: true },
// { id: 3, paid: true }
// ]
The keys remain actual boolean values rather than being converted into strings.
There is also an important detail about Object.groupBy(): it returns an object with a null prototype.
Consequently, this won't work:
grouped.hasOwnProperty("Food");
Use this instead when working with the object returned by Object.groupBy():
Object.hasOwn(grouped, "Food");
Both grouping methods are part of ES2024. If you're maintaining applications that support older browsers or JavaScript runtimes, check compatibility before replacing Lodash.
For modern projects, however, grouping data no longer requires an external utility library.
4. Flattening nested arrays with flat() and flatMap()
Imagine you're building an online shopping application where each order contains multiple products.
const orders = [
{
id: 101,
products: ["Keyboard", "Mouse"]
},
{
id: 102,
products: ["Monitor"]
},
{
id: 103,
products: ["Headphones", "Webcam"]
}
];
We want to retrieve a single array containing every product across all orders.
A common Lodash solution would be:
const products = _.flatMap(orders, "products");
JavaScript has had its own flatMap() method since ES2019.
const products = orders.flatMap(
order => order.products
);
console.log(products);
// [
// "Keyboard",
// "Mouse",
// "Monitor",
// "Headphones",
// "Webcam"
// ]
Conceptually, flatMap() performs a mapping operation followed by flattening the result by one level.
In other words, these two expressions produce equivalent results for ordinary arrays in this example.
orders.map(order => order.products).flat();
orders.flatMap(order => order.products);
The second version is slightly more concise and avoids explicitly creating the intermediate mapped array.
But there's another interesting use of flatMap() that many developers overlook.
Filtering and transforming in a single operation
Suppose we want to retrieve the email addresses of active users.
const users = [
{ email: "alex@example.com", active: true },
{ email: "sarah@example.com", active: false },
{ email: "john@example.com", active: true }
];
Normally, we would write:
const emails = users
.filter(user => user.active)
.map(user => user.email);
There's absolutely nothing wrong with this implementation.
However, flatMap() provides another option.
const emails = users.flatMap(user =>
user.active ? [user.email] : []
);
Returning an empty array removes an element from the result. Returning an array containing one or more elements adds those elements to the result.
This becomes particularly useful when transforming a single input into multiple output values.
For example, suppose we're generating search tags from product names.
const products = [
"Mechanical Keyboard",
"Wireless Mouse",
"USB Cable"
];
const tags = products.flatMap(product =>
product.toLowerCase().split(" ")
);
console.log(tags);
// [
// "mechanical",
// "keyboard",
// "wireless",
// "mouse",
// "usb",
// "cable"
// ]
Flattening arrays of unknown depth
Lodash also provides flattenDeep().
const numbers = [1, [2, [3, [4, 5]]]];
const flattened = _.flattenDeep(numbers);
The native equivalent for ordinary nested arrays is:
const flattened = numbers.flat(Infinity);
console.log(flattened);
// [1, 2, 3, 4, 5]
If you only want to flatten a specific number of levels, supply that number.
numbers.flat(1);
// [1, 2, [3, [4, 5]]]
numbers.flat(2);
// [1, 2, 3, [4, 5]]
numbers.flat(Infinity);
// [1, 2, 3, 4, 5]
One consideration is that native flat() and flatMap() have specific behaviour around sparse arrays, and they don't replicate every Lodash flattening rule for array-like objects.
For ordinary arrays, though, the native methods cover most everyday requirements.
5. Deep cloning objects with structuredClone()
This is probably one of the most useful additions to the modern JavaScript ecosystem.
Consider an application where users can edit their account settings.
const settings = {
theme: "dark",
notifications: {
email: true,
push: false
}
};
We want to create a copy of the settings so the user can make changes without modifying the original object.
Our first attempt might be:
const draft = { ...settings };
draft.notifications.email = false;
Unfortunately, this also changes the original settings.
console.log(settings.notifications.email);
// false
The spread operator creates a shallow copy. Nested objects remain shared references.
For years, one of the most convenient solutions was Lodash's cloneDeep().
const draft = _.cloneDeep(settings);
Modern browsers and Node.js also provide a built-in alternative.
const draft = structuredClone(settings);
draft.notifications.email = false;
console.log(settings.notifications.email);
// true
console.log(draft.notifications.email);
// false
The nested objects are now independent.
Isn't JSON.parse(JSON.stringify()) good enough?
You've probably encountered this JavaScript trick before.
const copy = JSON.parse(
JSON.stringify(original)
);
It works reasonably well for simple JSON-compatible data.
But consider this object:
const original = {
createdAt: new Date("2026-01-01"),
permissions: new Set(["read", "write"]),
preferences: new Map([
["theme", "dark"]
]),
lastLogin: undefined
};
After cloning it using JSON serialization:
const copy = JSON.parse(
JSON.stringify(original)
);
console.log(copy);
The result looks something like this:
{
createdAt: "2026-01-01T00:00:00.000Z",
permissions: {},
preferences: {}
}
Our Date became a string. The Set and Map lost their contents. The undefined property disappeared entirely.
Now try the same operation using structuredClone().
const copy = structuredClone(original);
console.log(copy.createdAt instanceof Date);
// true
console.log(copy.permissions instanceof Set);
// true
console.log(copy.preferences instanceof Map);
// true
console.log(Object.hasOwn(copy, "lastLogin"));
// true
The supported data types are preserved.
structuredClone() can also handle circular references.
const original = {
name: "Example"
};
original.self = original;
const copy = structuredClone(original);
console.log(copy.self === copy);
// true
Trying to serialize that same object using JSON.stringify() would throw an error.
Comparing the cloning methods
| Feature | Spread { ...obj } | JSON cloning | structuredClone() | _.cloneDeep() |
|---|---|---|---|---|
| Independent nested objects | No | Yes | Yes | Yes |
Preserves Date | Shared reference | No | Yes | Yes |
Preserves Map and Set | Shared reference | No | Yes | Yes |
Preserves undefined properties | Yes | No | Yes | Yes |
| Handles circular references | Not independently | No | Yes | Yes |
| Handles nested functions | Shared reference | No | No | Shared reference |
| External dependency | No | No | No | Yes |
When should you still use cloneDeep()?
Despite its usefulness, structuredClone() isn't a universal replacement for Lodash.
It cannot clone functions. Attempting to do so throws a DataCloneError.
const original = {
name: "Settings",
onSave: () => console.log("Saved")
};
const copy = structuredClone(original);
// DataCloneError
It also doesn't preserve custom class prototypes, property descriptors, or getter and setter definitions in the same way as the original object.
Lodash has its own cloning limitations, but it supports different behaviour and provides additional flexibility through functions such as cloneDeepWith().
For application state, API responses, configuration data, and other supported data structures, structuredClone() is often an excellent choice.
Just make sure you actually need a deep copy. Deep cloning a large object every time you update a single property can introduce unnecessary overhead.
Sometimes, selectively copying the affected properties is the better solution.
Bonus: Five more Lodash functions you can often replace
While researching native alternatives, there are several other familiar Lodash functions worth revisiting.
| Lodash | Native JavaScript |
|---|---|
_.includes(items, value) | items.includes(value) |
_.find(items, predicate) | items.find(predicate) |
_.every(items, predicate) | items.every(predicate) |
_.some(items, predicate) | items.some(predicate) |
_.compact(items) | items.filter(Boolean) |
These alternatives assume ordinary arrays and appropriate callback functions. Lodash additionally supports various collection types and iteratee shorthand expressions.
For example:
const activeUser = _.find(users, {
active: true
});
The native equivalent requires a callback.
const activeUser = users.find(
user => user.active === true
);
The additional characters are rarely a concern, but Lodash's shorthand syntax can still be convenient.
When Lodash is still worth keeping
Removing dependencies is a reasonable goal, but it shouldn't become an obsession.
There are still situations where Lodash provides functionality that doesn't have an equally convenient native equivalent.
| Lodash function | Why it remains useful |
|---|---|
_.debounce() | Configurable debouncing, cancellation and flushing |
_.throttle() | Controlling how frequently a function executes |
_.isEqual() | Deep structural equality comparisons |
_.merge() | Recursively merging objects |
_.orderBy() | Sorting collections using multiple criteria |
_.set() | Updating properties using dynamic nested paths |
_.chunk() | Splitting arrays into smaller groups |
You could implement many of these functions yourself.
But consider the edge cases, testing requirements, and maintenance responsibilities before doing so.
Replacing one well-tested library function with fifty lines of custom code isn't necessarily an improvement.
There is also no guarantee that native JavaScript will always be faster. Performance depends on the runtime, input data, implementation and workload.
The strongest argument for replacing straightforward Lodash functions is often simplicity, rather than performance.
A quick migration cheat sheet
| Task | Lodash | Native alternative |
|---|---|---|
| Remove duplicates | _.uniq(items) | [...new Set(items)] |
| Access nested properties | _.get(obj, path) | Optional chaining |
| Provide fallback values | _.get(obj, path, fallback) | Optional chaining with ?? |
| Group data | _.groupBy(items, fn) | Object.groupBy(items, fn) |
| Map and flatten | _.flatMap(items, fn) | items.flatMap(fn) |
| Flatten one level | _.flatten(items) | items.flat() |
| Flatten all levels | _.flattenDeep(items) | items.flat(Infinity) |
| Deep clone supported data | _.cloneDeep(obj) | structuredClone(obj) |
Treat this table as a migration starting point, not a guarantee that every function has identical behaviour.
Final thoughts
Lodash earned its place in the JavaScript ecosystem for good reasons.
It made everyday programming easier during a time when JavaScript lacked many of the features we now take for granted.
But our habits don't always evolve as quickly as the language does.
It's entirely possible to be writing modern React applications, using TypeScript, deploying containerised Node.js services, and still relying on utility functions that JavaScript has supported natively for years.
The next time you're about to import something from Lodash, spend a moment checking whether JavaScript already provides what you need.
You might discover that the best utility library for your next project is the language you're already using.
THE CONVERSATION
Comments
Questions, useful examples and different approaches are welcome. Keep the discussion thoughtful and on topic.
Loading comments…