Sorting & Iteration
Sorting & Iteration is a core JavaScript concept covering sorting & Iteration: - sort(): Sorts an array alphabetically. This topic is essential for academic learning, board exam preparation, and developing optimized real-world code.
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:
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a - b});
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.
const numbers1 = [45, 4, 9, 16, 25];
const numbers2 = numbers1.map(value => value * 2);
3. filter()
Creates a new array with all array elements that pass a test.
const over18 = numbers.filter(value => value > 18);
4. reduce()
Runs a function on each array element to produce (reduce it to) a single value.
let sum = numbers.reduce((total, value) => total + value);
Industry Standard
In React and modern JS development, map() and filter() are used constantly to render lists and manage data.