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.
Practice tasks
Reading is not enough. Try these without copying code, then compare with the lesson.
- Use map to square a list of numbers.
- Use filter to keep even numbers, and reduce to total them.
- Sort names alphabetically and explain the sort of numbers problem.
Common mistakes
- Mutating an array while looping over it.
- Forgetting that sort converts items to strings by default.
Quick check
Which method creates a new array from each item?
map.
What does reduce return?
A single accumulated value.