Choosing Between Array and Map in JavaScript
Source: Dev.to
The Hidden Cost of Array Lookups
Let’s consider a scenario in which we have a list of users and our task is to identify a specific user by their ID, update their data, or remove them from the list.
const users = [
{ id: '1', name: 'John Smith', age: 28 },
{ id: '2', name: 'Jane Doe', age: 34 },
{ id: '3', name: 'Bob Johnson', age: 42 }
];
The first thought that often comes to mind is to use methods available on arrays such as find(), filter(), or splice(). All of those work, but they come with some cost.
// Looking up a user
const user = users.find(u => u.id === '2');
// Removing a user from the list
const updatedUsers = users.filter(u => u.id !== '2');
Why This Hurts Performance
Every time you use the find() method, JavaScript has to iterate through the elements one by one until it finds a match. For small arrays this is unnoticeable, but as your data grows, these O(n) operations start to add up, especially when performed repeatedly.
The O(1) Fix: Map
This is where Map comes in handy, designed specifically for key‑based operations.
// Transform array to map with ID as a key
const usersMap = new Map(users.map(u => [u.id, u]));
console.log(usersMap);
// Map(3) {
// '1' => { id: '1', name: 'John Smith', age: 28 },
// '2' => { id: '2', name: 'Jane Doe', age: 34 },
// '3' => { id: '3', name: 'Bob Johnson', age: 42 }
// }
Looking up, adding, or removing items by key happens in O(1) constant time, regardless of how many items you have stored.
// Verifying user existence
const userExists = usersMap.has('2');
// Getting user by ID
const user = usersMap.get('2');
// Updating user data
usersMap.set('2', { id: '2', name: 'Jane Doe Updated', age: 35 });
// Removing user
usersMap.delete('1');
When Arrays Still Make Sense
That said, arrays aren’t obsolete. In many scenarios—especially when order matters, or when you’re performing operations like mapping, filtering, or sorting—arrays are still the right choice. Maps shine when your primary interaction is lookup by key.
- If you just need to list items, filter them, or render them in UI order, an array is simpler.
- If you often search by ID, toggle specific items, or sync updates efficiently,
Mapwill pay off in performance and clarity.