Sorting & Iteration¶
Sorting Arrays¶
sort(): Sorts an array alphabetically.reverse(): Reverses the elements in an array.
Numeric Sort¶
By default, the sort() function sorts values as strings (so "25" is bigger than "100" because "2" > "1"). To sort numbers correctly:
Array Iteration (High Order Functions)¶
1. forEach()¶
Calls a function once for each array element.
const numbers = [45, 4, 9, 16, 25];
numbers.forEach(myFunction);
function myFunction(value) {
console.log(value);
}
2. map()¶
Creates a new array by performing a function on each array element.
3. filter()¶
Creates a new array with all array elements that pass a test.
4. reduce()¶
Runs a function on each array element to produce (reduce it to) a single value.
Industry Standard
In React and modern JS development, map() and filter() are used constantly to render lists and manage data.