Array Operations
By Syncfusion®, Inc. · Last updated
Transforming arrays with forEach, map, filter, reduce and flatMap, searching with find, findIndex, includes, indexOf, some and every, sorting numbers, text and objects with comparators, toSorted and toReversed, and grouping with Object.groupBy and Map.groupBy to count, total, average and rank.
What Are Array Operations?
Array method = a built-in tool that works through every item of an array for you.
- Transform:
map(),filter(),reduce()build a new list or one answer. - Search:
find(),includes(),some(),every()look for items. - Sort and group:
toSorted()andObject.groupBy()put items in order or in groups.
Simple lesson: you say what to do with one item; the method does it for all of them.
A Real-World Example
A shop has a list of orders.
It shows only paid orders (filter), the total sales (reduce) and the biggest three orders (toSorted + slice).
Each job is one line of code, not a whole loop.
[120, 45, 300, 80]
filter(p > 50) [120, 300, 80]
map(p × 2) [240, 600, 160]
reduce(sum) 1000
Chain methods: each one gives the next one its input.
A list flows through filter, map and reduce, and becomes one number.
Most methods here return a new array and leave the original alone. The lesson says clearly when one changes the original.
What You Will Learn
forEach(),map(),filter()andreduce().find(),findIndex(),includes(),indexOf(),some()andevery().- Sorting numbers, text and objects with
sort()andtoSorted(). reverse()andtoReversed().- Grouping, counting, totals, averages and top-N lists.
Transforming arrays
Most of these methods take a function. The method calls it once for each item.
| Method | Gives back |
|---|---|
forEach() | Nothing (undefined). It only does an action. |
map() | A new array, same length, each item changed |
filter() | A new array with only the items that passed |
reduce() | One value, such as a total |
forEach()
Use it to do something for each item, like printing. It returns undefined.
Printing a line for each item in a cart
const cart = ["Notebook", "Pen", "Backpack"];
cart.forEach((item, index) => {
console.log(`${index + 1}. ${item}`);
});
const result = cart.forEach((item) => item.toUpperCase());
console.log("forEach returned:", result);
Expected output:
1. Notebook
2. Pen
3. Backpack
forEach returned: undefined
map()
One new value for each item. The new array has the same length; the original stays the same.
Adding tax to every price
const prices = [10, 25, 40];
const withTax = prices.map((price) => price * 1.2);
const labels = prices.map((price) => `$${price.toFixed(2)}`);
console.log("withTax:", withTax);
console.log("labels: ", labels);
console.log("prices: ", prices);
Expected output:
withTax: [
12,
30,
48
]
labels: [
"$10.00",
"$25.00",
"$40.00"
]
prices: [
10,
25,
40
]
filter()
Keeps the items where your function returns true. Filter first, then map to pick fields.
Keeping only the books that are in stock
const books = [
{ title: "Deep Work", price: 18, inStock: true },
{ title: "Atomic Habits", price: 22, inStock: false },
{ title: "Clean Code", price: 35, inStock: true },
];
const available = books.filter((book) => book.inStock);
const underTwenty = books.filter((book) => book.price < 20);
console.log("available: ", available.map((book) => book.title));
console.log("under $20: ", underTwenty.map((book) => book.title));
Expected output:
available: [
"Deep Work",
"Clean Code"
]
under $20: [
"Deep Work"
]
reduce()
Combines all items into one value. It keeps a running result, starting from the value you pass (0 here).
A total and a largest value from one list
const sales = [120, 45, 300, 80];
const total = sales.reduce((runningTotal, sale) => runningTotal + sale, 0);
const largest = sales.reduce((biggest, sale) => (sale > biggest ? sale : biggest), 0);
console.log("total: ", total);
console.log("largest:", largest);
Expected output:
total: 545
largest: 300
For the total: 0 + 120 = 120, then 165, 465, and finally 545.
Always pass the starting value, such as 0. Without it, an empty array throws TypeError: Reduce of empty array with no initial value.
Searching arrays
Searching never changes the array. Some methods give an item, some a position, some true/false.
find()
Returns the first matching item, or undefined. Use ?. and ?? to stay safe when nothing matches.
Finding one user by id
const users = [
{ id: 7, name: "Asha" },
{ id: 12, name: "Ravi" },
{ id: 19, name: "Meera" },
];
const ravi = users.find((user) => user.id === 12);
const missing = users.find((user) => user.id === 99);
console.log("found: ", ravi.name);
console.log("missing:", missing);
console.log("safe: ", missing?.name ?? "no such user");
Expected output:
found: Ravi
missing: undefined
safe: no such user
findIndex()
Returns the position of the first match, or -1 for "not found".
Finding the position of a user
const users = [
{ id: 7, name: "Asha" },
{ id: 12, name: "Ravi" },
{ id: 19, name: "Meera" },
];
console.log("Ravi is at:", users.findIndex((user) => user.id === 12));
console.log("id 99 is at:", users.findIndex((user) => user.id === 99));
Expected output:
Ravi is at: 1
id 99 is at: -1
includes()
Is this exact value in the array? true or false. Upper and lower case count as different.
Checking a guest list
const guests = ["Asha", "Ravi", "Meera"];
console.log("Ravi invited? ", guests.includes("Ravi"));
console.log("Kabir invited?", guests.includes("Kabir"));
console.log("ravi invited? ", guests.includes("ravi"));
Expected output:
Ravi invited? true
Kabir invited? false
ravi invited? false
indexOf()
The older way: the position of a value, or -1. Careful: position 0 is falsy in an if.
indexOf() gives a position, and 0 is a real position
const guests = ["Asha", "Ravi", "Meera"];
console.log("indexOf Asha: ", guests.indexOf("Asha"));
console.log("indexOf Kabir:", guests.indexOf("Kabir"));
if (guests.indexOf("Asha")) {
console.log("truthy check: found Asha");
} else {
console.log("truthy check: did NOT find Asha");
}
Expected output:
indexOf Asha: 0
indexOf Kabir: -1
truthy check: did NOT find Asha
Compare with !== -1, or just use includes().
some()
Does at least one item match? Stops at the first match.
Is any order over the limit?
const orderTotals = [45, 120, 380, 60];
console.log("any over 300?", orderTotals.some((total) => total > 300));
console.log("any over 500?", orderTotals.some((total) => total > 500));
Expected output:
any over 300? true
any over 500? false
Difference between some() and find()
| Method | some() | find() |
|---|---|---|
| Question | Does any item match? | Which item matches first? |
| Returns | true or false | The item, or undefined |
every()
Do all items match? Stops at the first failure. An empty array gives true.
Did every student pass?
const scores = [72, 88, 45, 91];
const noScores = [];
console.log("all passed (>= 50)?", scores.every((score) => score >= 50));
console.log("all above 40? ", scores.every((score) => score > 40));
console.log("empty list: ", noScores.every((score) => score >= 50));
Expected output:
all passed (>= 50)? false
all above 40? true
empty list: true
Sorting arrays
Sorting puts items in order. Without help, sort() compares items as text.
sort()
sort() changes the original array. With no function, numbers sort like words: "100" before "25".
sort() with no comparator sorts numbers as text
const scores = [100, 25, 9, 1000];
scores.sort();
console.log("sorted as text:", scores);
Expected output:
sorted as text: [
100,
1000,
25,
9
]
Sort with comparator
A comparator (a, b) => number decides the order:
- negative →
afirst - positive →
bfirst 0→ keep their order
Watching a comparator decide
const scores = [30, 10, 20];
const sorted = scores.toSorted((a, b) => {
const answer = a - b;
console.log(`compare ${a} and ${b}: ${answer}`);
return answer;
});
console.log("sorted:", sorted);
A comparator must return a number. (a, b) => a > b returns true/false, and the result is only partly sorted.
Sorting numbers
(a, b) => a - b = smallest first. (a, b) => b - a = largest first.
Numbers ascending and descending
const scores = [100, 25, 9, 1000];
console.log("smallest first:", scores.toSorted((a, b) => a - b));
console.log("largest first: ", scores.toSorted((a, b) => b - a));
Expected output:
smallest first: [
9,
25,
100,
1000
]
largest first: [
1000,
100,
25,
9
]
Sorting text
The default puts capitals first and handles letters like É oddly. localeCompare() sorts like a dictionary.
Default text order and dictionary order
const names = ["ravi", "Asha", "Émile", "meera", "Zara"];
console.log("default: ", names.toSorted());
console.log("localeCompare:", names.toSorted((a, b) => a.localeCompare(b)));
Expected output:
default: [
"Asha",
"Zara",
"meera",
"ravi",
"Émile"
]
localeCompare: [
"Asha",
"Émile",
"meera",
"ravi",
"Zara"
]
Sorting objects
Compare one property. If two are equal, add a second comparison (a tie-break).
Sorting students by grade, then by name
const students = [
{ name: "Ravi", grade: 88 },
{ name: "Asha", grade: 92 },
{ name: "Meera", grade: 88 },
{ name: "Kabir", grade: 75 },
];
const ranked = students.toSorted(
(a, b) => b.grade - a.grade || a.name.localeCompare(b.name),
);
for (const student of ranked) {
console.log(student.grade, student.name);
}
Expected output:
92 Asha
88 Meera
88 Ravi
75 Kabir
toSorted()
Same as sort(), but returns a sorted copy. The original keeps its order.
sort() changes the original, toSorted() does not
const original = [30, 10, 20];
const sortedCopy = original.toSorted((a, b) => a - b);
console.log("toSorted, original:", original);
console.log("toSorted, copy: ", sortedCopy);
const another = [30, 10, 20];
const returned = another.sort((a, b) => a - b);
console.log("sort, original: ", another);
console.log("sort returned the same array:", returned === another);
Expected output:
toSorted, original: [
30,
10,
20
]
toSorted, copy: [
10,
20,
30
]
sort, original: [
10,
20,
30
]
sort returned the same array: true
Use toSorted() by default. Use sort() only when changing the array is the point.
reverse() vs toReversed()
reverse() flips the original. toReversed() gives a flipped copy.
Newest first, with and without changing the original
const history = ["Login", "View cart", "Checkout"];
const newestFirst = history.toReversed();
console.log("toReversed copy:", newestFirst);
console.log("history after: ", history);
history.reverse();
console.log("after reverse():", history);
Expected output:
toReversed copy: [
"Checkout",
"View cart",
"Login"
]
history after: [
"Login",
"View cart",
"Checkout"
]
after reverse(): [
"Checkout",
"View cart",
"Login"
]
Grouping
Grouping = putting items into buckets by a shared value, the key (region, category, grade). The examples use this list of sales:
const sales = [
{ id: 1, region: "North", product: "Lamp", amount: 120 },
{ id: 2, region: "South", product: "Desk", amount: 340 },
{ id: 3, region: "North", product: "Chair", amount: 85 },
{ id: 4, region: "East", product: "Lamp", amount: 60 },
{ id: 5, region: "South", product: "Chair", amount: 90 },
{ id: 6, region: "North", product: "Desk", amount: 310 },
];
Object.groupBy()
Your function returns the key; items with the same key go into the same array.
Grouping sales by region
const sales = [
{ id: 1, region: "North", product: "Lamp", amount: 120 },
{ id: 2, region: "South", product: "Desk", amount: 340 },
{ id: 3, region: "North", product: "Chair", amount: 85 },
{ id: 4, region: "East", product: "Lamp", amount: 60 },
{ id: 5, region: "South", product: "Chair", amount: 90 },
{ id: 6, region: "North", product: "Desk", amount: 310 },
];
const byRegion = Object.groupBy(sales, (sale) => sale.region);
console.log("keys:", Object.keys(byRegion));
console.log("North ids:", byRegion.North.map((sale) => sale.id));
Expected output:
keys: [
"North",
"South",
"East"
]
North ids: [
1,
3,
6
]
Map.groupBy()
The same, but returns a Map, which keeps keys as their real type. Object.groupBy() turns keys into text.
Grouping by a number keeps the key a number
const sales = [
{ id: 1, region: "North", product: "Lamp", amount: 120 },
{ id: 2, region: "South", product: "Desk", amount: 340 },
{ id: 3, region: "North", product: "Chair", amount: 85 },
{ id: 4, region: "East", product: "Lamp", amount: 60 },
{ id: 5, region: "South", product: "Chair", amount: 90 },
{ id: 6, region: "North", product: "Desk", amount: 310 },
];
const bySize = (sale) => (sale.amount >= 100 ? 100 : 0);
const asObject = Object.groupBy(sales, bySize);
const asMap = Map.groupBy(sales, bySize);
console.log("object keys:", Object.keys(asObject));
console.log("map keys: ", [...asMap.keys()]);
console.log("big sales: ", asMap.get(100).map((sale) => sale.id));
Expected output:
object keys: [
"0",
"100"
]
map keys: [
100,
0
]
big sales: [
1,
2,
6
]
Object.groupBy() and Map.groupBy() are new. They work in current browsers and Node.js 21+. Older code does the same job with reduce().
Counting items by group
Each group is an array, so its length is the count.
How many sales each region made
const sales = [
{ id: 1, region: "North", product: "Lamp", amount: 120 },
{ id: 2, region: "South", product: "Desk", amount: 340 },
{ id: 3, region: "North", product: "Chair", amount: 85 },
{ id: 4, region: "East", product: "Lamp", amount: 60 },
{ id: 5, region: "South", product: "Chair", amount: 90 },
{ id: 6, region: "North", product: "Desk", amount: 310 },
];
const byRegion = Object.groupBy(sales, (sale) => sale.region);
for (const [region, regionSales] of Object.entries(byRegion)) {
console.log(region.padEnd(6), regionSales.length);
}
Expected output:
North 3
South 2
East 1
Total and average by group
Total = reduce() the group's amounts. Average = total ÷ length.
Revenue and average sale per region
const sales = [
{ id: 1, region: "North", product: "Lamp", amount: 120 },
{ id: 2, region: "South", product: "Desk", amount: 340 },
{ id: 3, region: "North", product: "Chair", amount: 85 },
{ id: 4, region: "East", product: "Lamp", amount: 60 },
{ id: 5, region: "South", product: "Chair", amount: 90 },
{ id: 6, region: "North", product: "Desk", amount: 310 },
];
const byRegion = Object.groupBy(sales, (sale) => sale.region);
for (const [region, regionSales] of Object.entries(byRegion)) {
const total = regionSales.reduce((sum, sale) => sum + sale.amount, 0);
const average = total / regionSales.length;
console.log(region.padEnd(6), "total:", total, "average:", average.toFixed(2));
}
Expected output:
North total: 515 average: 171.67
South total: 430 average: 215.00
East total: 60 average: 60.00
Top-N items
Top N = the N biggest items. Sort largest first with toSorted(), then keep slice(0, n).
The three biggest sales, and the top sale in each region
const sales = [
{ id: 1, region: "North", product: "Lamp", amount: 120 },
{ id: 2, region: "South", product: "Desk", amount: 340 },
{ id: 3, region: "North", product: "Chair", amount: 85 },
{ id: 4, region: "East", product: "Lamp", amount: 60 },
{ id: 5, region: "South", product: "Chair", amount: 90 },
{ id: 6, region: "North", product: "Desk", amount: 310 },
];
const topThree = sales.toSorted((a, b) => b.amount - a.amount).slice(0, 3);
console.log("top three:", topThree.map((sale) => `${sale.product} ${sale.amount}`));
const byRegion = Object.groupBy(sales, (sale) => sale.region);
for (const [region, regionSales] of Object.entries(byRegion)) {
const best = regionSales.toSorted((a, b) => b.amount - a.amount)[0];
console.log("best in", region.padEnd(6), best.product, best.amount);
}
Expected output:
top three: [
"Desk 340",
"Desk 310",
"Lamp 120"
]
best in North Desk 310
best in South Desk 340
best in East Lamp 60
Array Operations on a Web Page
Type in the box to filter() products, pick a sort order, and show the total with reduce().
Search, sort and total a product list
const products = [
{ name: "Steel bottle", price: 299 },
{ name: "Lunch box", price: 349 },
{ name: "Notebook", price: 60 },
{ name: "Pencil box", price: 120 },
{ name: "School bag", price: 899 },
];
const search = document.querySelector("#search");
const list = document.querySelector("#products");
const status = document.querySelector("#status");
function draw() {
const text = search.value.toLowerCase();
const shown = products
.filter((p) => p.name.toLowerCase().includes(text))
.toSorted((a, b) => a.price - b.price);
list.innerHTML = "";
shown.forEach((p) => {
const li = document.createElement("li");
li.textContent = `${p.name} — ₹${p.price}`;
list.append(li);
});
const total = shown.reduce((sum, p) => sum + p.price, 0);
status.textContent = `${shown.length} items, cheapest first, worth ₹${total}`;
}
search.addEventListener("input", draw);
draw();
console.log("Try typing 'box'.");
Easy way to remember: map = change each, filter = keep some, reduce = squash into one, find = get one.
TL;DR
mapchanges each item,filterkeeps some,reducemakes one value;forEachreturns nothing.findgives an item orundefined;findIndex/indexOfgive a position or-1.includes,someandeveryanswer yes or no.- Sort numbers with
(a, b) => a - b. PrefertoSorted()andtoReversed(). Object.groupBy()makes buckets;lengthcounts them,reducetotals them.
Try this
In Sorting objects, remove the name tie-break. Ravi now comes before Meera, because he was first in the original list. JavaScript's sort is stable: equal items keep their order.
Check Yourself
Common mistakes
| Mistake | Wrong idea | Correct idea | What goes wrong |
|---|---|---|---|
map((x) => { x * 2 }) | Arrows always return | { } needs return | An array of undefined |
const r = list.forEach(...) | forEach returns results | It returns undefined | r is undefined |
reduce(fn) with no start | The start is optional | Pass 0 (or [], {}) | Empty arrays throw a TypeError |
if (list.indexOf(x)) | Found means truthy | Position 0 is falsy | The first item is "not found" |
[100, 25, 9].sort() | It sorts numbers | It sorts as text | 100, 25, 9 |
sort() inside a helper | It returns a copy | It changes the caller's array | Another list is reordered |
Quick reference
| Syntax | Meaning |
|---|---|
array.forEach((item, i) => ...) | run code for each item, returns undefined |
array.map((item) => newValue) | a new array with one new value per item |
array.filter((item) => test) | a new array of the items that pass |
array.reduce((acc, item) => next, start) | one value built from every item |
array.flatMap((item) => [...]) | map, then flatten one level |
array.find((item) => test) | the first matching item, or undefined |
array.findIndex((item) => test) | the first matching position, or -1 |
array.includes(value) | true if the value is in the array |
array.indexOf(value) | the position of the value, or -1 |
array.some((item) => test) | true if at least one item passes |
array.every((item) => test) | true if every item passes, and for an empty array |
(a, b) => a - b / (a, b) => b - a | numbers smallest first / largest first |
(a, b) => a.name.localeCompare(b.name) | text in dictionary order |
sort(cmp) / toSorted(cmp) | sort in place / sort a copy |
reverse() / toReversed() | flip in place / flip a copy |
Object.groupBy(array, (item) => key) | an object of arrays, one per key |
Map.groupBy(array, (item) => key) | a Map of arrays, keys keep their type |
array.toSorted(cmp).slice(0, n) | the top n items |
Exercises
What to Remember
- Describe one item; the method handles them all.
- Know which methods make copies (
map,filter,toSorted) and which change the original (sort,reverse). - Group, then count, total or rank.
Next: Object Fundamentals. Create objects, read and change their properties, and give them methods.