Creating arrays
const marks = [78, 92, 65, 88];
console.log(marks[0]); // 78 (first item)
console.log(marks.length); // 4
marks[1] = 95; // change an itemAdding and removing
const list = ["a", "b"];
list.push("c"); // add to end
list.pop(); // remove from end
list.unshift("z"); // add to start
list.shift(); // remove from startTransforming with map, filter and reduce
These are the most important array methods. They return new arrays or values and do not change the original.
<script>
const marks = [45, 78, 92, 30, 66];
const grace = marks.map(m => m + 5); // add 5 to each
const passed = marks.filter(m => m >= 40); // keep matching
const total = marks.reduce((sum, m) => sum + m, 0);
document.write("With grace: " + grace.join(", ") + "<br>");
document.write("Passed: " + passed.join(", ") + "<br>");
document.write("Average: " + (total / marks.length).toFixed(1));
</script>Searching
marks.includes(92); // true
marks.indexOf(30); // 3
marks.find(m => m > 60); // first match: 78
marks.some(m => m < 40); // true if any match
marks.every(m => m >= 30); // true if all matchSorting and slicing
[10, 2, 33].sort((a, b) => a - b); // [2, 10, 33]
["b", "a"].sort(); // ["a", "b"]
marks.slice(1, 3); // items at index 1 and 2
[..."abc"]; // ["a", "b", "c"]Always pass a compare function to sort for numbers, because the default sorts as text.
Practice
Given an array of student objects with names and marks, print the names of students who scored above 75, sorted by marks from highest to lowest.