# Searching & Sorting Arrays — JavaScript Fundamentals: From Syntax to Async

Source: https://www.geekswithgeeks.com/en/javascript/js-array-search-sort

> Find items with find, some, every and includes, and sort arrays correctly with comparator functions.

## Finding items

`find` returns the first match, `some` and `every` return booleans and `includes` checks for a value.

```javascript
const users = [{ id: 1, age: 17 }, { id: 2, age: 30 }];
users.find(u => u.age > 18);      // { id: 2, age: 30 }
users.some(u => u.age < 18);      // true
users.every(u => u.age > 10);     // true
[1, 2, 3].includes(2);            // true
```

## Sorting

`sort()` compares as strings by default. Always pass a comparator for numbers, and copy first with `toSorted` or a spread.

```javascript
[10, 9, 1].sort();                 // [1, 10, 9]  (string order!)
[10, 9, 1].sort((a, b) => a - b);  // [1, 9, 10]
const sorted = [...nums].sort((a, b) => a - b); // keeps nums intact
```

Quick check

**Quiz:** Why does [10, 9, 1].sort() give [1, 10, 9]?

- [x] It compares items as strings by default
- [ ] Sorting is random
- [ ] Numbers cannot be sorted
- [ ] It sorts by length

*Answer:* It compares items as strings by default. Pass (a, b) => a - b for numeric order.
