JavaScript: Data structures – code examples
Contents
Working with arrays
Use case: Manage collections of values: add, sort, filter.
const zahlen = [5, 3, 8, 1];
zahlen.push(10);
zahlen.sort((a, b) => a - b);
console.log(zahlen);
console.log(zahlen.filter(z => z > 3).map(z => z * 2));
console.log(zahlen.reduce((s, z) => s + z, 0), Math.max(...zahlen), zahlen.length);sort needs a compare function for numbers; filter, map and reduce return new values.
Object as a dictionary
Use case: Store mappings, e.g. configurations or JSON-like data.
const person = { name: "Ada", alter: 36 };
person.stadt = "London";
for (const [schluessel, wert] of Object.entries(person)) {
console.log(schluessel, "=", wert);
}
console.log(person.email ?? "no email");Objects serve as dictionaries; Object.entries returns the pairs. For arbitrary key types there is also the Map class. ?? returns a default value for undefined.
Sorting by a custom criterion
Data structures#sort#compare#localeCompare
Use case: Order records by a field, e.g. users by age or name.
const nutzer = [
{ name: "Ada", alter: 36 },
{ name: "Bob", alter: 25 },
{ name: "Cleo", alter: 30 }
];
const nachAlter = [...nutzer].sort((a, b) => a.alter - b.alter);
console.log(nachAlter.map(n => n.name));
const nachName = [...nutzer].sort((a, b) => b.name.localeCompare(a.name));
console.log(nachName.map(n => n.name));sort modifies the array itself – so copy it first with [...nutzer]. localeCompare sorts text in a language-aware way.
Removing duplicates & sets
Data structures#set#unique#spread
Use case: Filter duplicate entries, form the intersection and union of two lists.
const zahlen = [1, 2, 2, 3, 3, 3];
console.log([...new Set(zahlen)]);
const a = new Set([1, 2, 3]);
const b = new Set([2, 3, 4]);
console.log([...a].filter(x => b.has(x))); // intersection
console.log([...new Set([...a, ...b])]); // unionSet stores each value only once; with spread it becomes an array again.
Grouping data with reduce
Data structures#reduce#group#groupBy
Use case: Organize orders by customer, products by category or logs by level.
const produkte = [
{ name: "Apple", typ: "Fruit" },
{ name: "Carrot", typ: "Vegetable" },
{ name: "Pear", typ: "Fruit" }
];
const gruppen = produkte.reduce((acc, p) => {
(acc[p.typ] ??= []).push(p.name);
return acc;
}, {});
console.log(gruppen);??= creates the array only if it is missing. In new engines, Object.groupBy(produkte, p => p.typ) does this for you.