Searching & Sorting

Searching

Example

const nums = [5, 12, 8, 130, 44];
console.log(nums.includes(8));
console.log(nums.indexOf(130));
console.log(nums.find(n => n > 10));
console.log(nums.findIndex(n => n > 10));
console.log(nums.some(n => n > 100), nums.every(n => n > 1));

Output

true
3
12
1
true true

Sorting

Example

sort() converts to strings by default, so numbers need a compare function. toSorted() returns a sorted copy:

const nums = [10, 1, 25, 3];
console.log([...nums].sort());                 // string order!
console.log([...nums].sort((a, b) => a - b));  // ascending
console.log(nums.toSorted((a, b) => b - a));   // descending copy
const users = [{ name: "Vikram", age: 30 }, { name: "Asha", age: 24 }];
console.log(users.toSorted((a, b) => a.name.localeCompare(b.name)).map(u => u.name));

Output

[ 1, 10, 25, 3 ]
[ 1, 3, 10, 25 ]
[ 25, 10, 3, 1 ]
[ 'Asha', 'Vikram' ]

Other Useful Methods

Example

console.log([3, [4, [5]]].flat(Infinity));
console.log(["a", "b", "c"].join(" - "));
console.log(Array.from({ length: 5 }, (_, i) => i * i));
console.log([1, 2, 2, 3, 3, 3].filter((v, i, arr) => arr.indexOf(v) === i));
console.log([...new Set([1, 2, 2, 3])]);

Output

[ 3, 4, 5 ]
a - b - c
[ 0, 1, 4, 9, 16 ]
[ 1, 2, 3 ]
[ 1, 2, 3 ]

Exercise

Exercise: Given const words = ["sql", "html", "css", "javascript"], create an array of the words longer than 3 characters, in uppercase.

Show answer
const result = words.filter(w => w.length > 3).map(w => w.toUpperCase());
// ["HTML", "JAVASCRIPT"]