JavaScriptintermediate 9 min
Lists of values, and the methods that add, remove, search and transform them.
How to create an array, read and change items, and use push, pop, map, filter and reduce.
Almost every program handles lists: a shopping cart, a list of users, search results. Arrays are the built-in list, and their methods save you from writing loops by hand.
An array is an ordered list of values in square brackets. Each item has an index, starting at 0.
Common methods:
push(x) adds to the end. pop() removes from the end.unshift(x) adds to the start. shift() removes from the start.includes(x) checks whether a value is in the array.indexOf(x) gives its position, or -1.slice(a, b) copies a part without changing the original.Three methods run a function on each item and are the most useful of all:
map(fn) makes a new array by transforming every item.filter(fn) makes a new array with only the items where fn returns true.reduce(fn, start) combines all items into one value, such as a sum.map multiplies every price by 1.1 and returns a new array (about 132, 49.5, 330, 88, with rounding noise).filter keeps only the prices under 100: [ 45, 80 ].reduce starts at 0 and adds each price: 120 + 45 + 300 + 80 = 545.push(60) adds an item to the original array, so its length becomes 5.includes(300) is true.Use filter to keep only the prices over 100, then map to halve them.
map to change the original array. It returns a new one.reduce, which can break on empty arrays.length - 1.slice when you meant splice. slice copies, splice modifies.push and pop change the end.map transforms, filter selects, reduce combines.Next: objects, for grouping related data.
const fruits = ["apple", "banana", "cherry"];
console.log(fruits[0]); // apple
console.log(fruits.length); // 3const prices = [120, 45, 300, 80];
const withTax = prices.map((p) => p * 1.1);
console.log(withTax);
const cheap = prices.filter((p) => p < 100);
console.log(cheap);
const total = prices.reduce((sum, p) => sum + p, 0);
console.log(total);
prices.push(60);
console.log(prices.length);
console.log(prices.includes(300));