# Array Operations

Course: [JavaScript](https://www.devtutorials.ai/learn/javascript) · Section: Arrays
Source: https://www.devtutorials.ai/learn/javascript/arrays/array-operations

> 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()` and `Object.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.

<figure className="ts-fig">
  <svg viewBox="0 0 560 180" role="img" aria-label="Four prices go through three machines. filter keeps prices over 50, map adds tax, reduce adds them into one total." width="100%">
    <rect x="0" y="0" width="560" height="180" rx="12" fill="#f8fafc" stroke="#e2e8f0" />
    <text x="20" y="40" fontSize="13" fontFamily="monospace" fill="#1e40af">[120, 45, 300, 80]</text>
    <rect x="30" y="70" width="140" height="44" rx="8" fill="#eff6ff" stroke="#2563eb" />
    <text x="100" y="90" textAnchor="middle" fontSize="12" fill="#1e40af">filter(p &gt; 50)</text>
    <text x="100" y="106" textAnchor="middle" fontSize="11" fontFamily="monospace" fill="#1e40af">[120, 300, 80]</text>
    <rect x="210" y="70" width="140" height="44" rx="8" fill="#fefce8" stroke="#ca8a04" />
    <text x="280" y="90" textAnchor="middle" fontSize="12" fill="#854d0e">map(p × 2)</text>
    <text x="280" y="106" textAnchor="middle" fontSize="11" fontFamily="monospace" fill="#854d0e">[240, 600, 160]</text>
    <rect x="390" y="70" width="140" height="44" rx="8" fill="#f0fdf4" stroke="#16a34a" />
    <text x="460" y="90" textAnchor="middle" fontSize="12" fill="#166534">reduce(sum)</text>
    <text x="460" y="106" textAnchor="middle" fontSize="11" fontFamily="monospace" fill="#166534">1000</text>
    <circle r="7" cy="92" fill="#2563eb"><animate attributeName="cx" values="20;30;210;390;540" keyTimes="0;0.1;0.4;0.7;1" dur="4s" repeatCount="indefinite" /></circle>
    <text x="280" y="150" textAnchor="middle" fontSize="12" fill="#475569">Chain methods: each one gives the next one its input.</text>
  </svg>
  <figcaption>A list flows through filter, map and reduce, and becomes one number.</figcaption>
</figure>

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

1. `forEach()`, `map()`, `filter()` and `reduce()`.
2. `find()`, `findIndex()`, `includes()`, `indexOf()`, `some()` and `every()`.
3. Sorting numbers, text and objects with `sort()` and `toSorted()`.
4. `reverse()` and `toReversed()`.
5. 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`.

```js runnable title="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:

```text
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.

```js runnable title="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:

```text
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.

```js runnable title="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:

```text
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).

```js runnable title="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:

```text
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.

```js runnable title="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:

```text
found:   Ravi
missing: undefined
safe:    no such user
```

### `findIndex()`

Returns the **position** of the first match, or `-1` for "not found".

```js runnable title="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:

```text
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.

```js runnable title="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:

```text
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`.

```js runnable title="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:

```text
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.

```js runnable title="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:

```text
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`.

```js runnable title="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:

```text
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"`.

```js runnable title="sort() with no comparator sorts numbers as text"
const scores = [100, 25, 9, 1000];

scores.sort();

console.log("sorted as text:", scores);
```

Expected output:

```text
sorted as text: [
  100,
  1000,
  25,
  9
]
```

### Sort with comparator

A **comparator** `(a, b) => number` decides the order:

- negative → `a` first
- positive → `b` first
- `0` → keep their order

```js runnable title="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.

```js runnable title="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:

```text
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.

```js runnable title="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:

```text
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**).

```js runnable title="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:

```text
92 Asha
88 Meera
88 Ravi
75 Kabir
```

### `toSorted()`

Same as `sort()`, but returns a **sorted copy**. The original keeps its order.

```js runnable title="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:

```text
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.

```js runnable title="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:

```text
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:

```js
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.

```js runnable title="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:

```text
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.

```js runnable title="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:

```text
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.

```js runnable title="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:

```text
North  3
South  2
East   1
```

### Total and average by group

Total = `reduce()` the group's amounts. Average = total ÷ `length`.

```js runnable title="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:

```text
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)`.

```js runnable title="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:

```text
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()`.

```js runnable preview="product-list" title="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

- `map` changes each item, `filter` keeps some, `reduce` makes one value; `forEach` returns nothing.
- `find` gives an item or `undefined`; `findIndex`/`indexOf` give a position or `-1`.
- `includes`, `some` and `every` answer yes or no.
- Sort numbers with `(a, b) => a - b`. Prefer `toSorted()` and `toReversed()`.
- `Object.groupBy()` makes buckets; `length` counts them, `reduce` totals 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

<div className="tscroll">

| 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 |

</div>

## 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.
