Array Uses in Web Development
Most data a web page receives, whether from an API, a JSON file or a form, arrives as an array of objects. Before it can be shown, it usually has to be narrowed down, put in order, totalled and turned into elements. The array methods do each of these jobs in one step, and because most of them return a new array, they can be chained into a short pipeline that reads in the order the work happens.
The examples on this page use this list of products, which stands in for the JSON a shop’s API might return. Prices are in pence, so that the sums involve only whole numbers.
const products = [ { id: 'p1', name: 'Desk lamp', category: 'lighting', price: 3499, stock: 12 }, { id: 'p2', name: 'Floor lamp', category: 'lighting', price: 8900, stock: 0 }, { id: 'p3', name: 'Bookcase', category: 'furniture', price: 12900, stock: 3 }, { id: 'p4', name: 'Side table', category: 'furniture', price: 4500, stock: 7 }, { id: 'p5', name: 'Cushion', category: 'textiles', price: 1500, stock: 40 },];
const formatPrice = (pence) => `£${(pence / 100).toFixed(2)}`;Filter, sort and map
Section titled “Filter, sort and map”A typical listing keeps only some items, puts them in order, and turns each one into something to display. filter() keeps the items for which its callback returns true, toSorted() returns a sorted copy, and map() turns each item into a new value.
const available = products .filter((product) => product.stock > 0) .toSorted((a, b) => a.price - b.price) .map((product) => `${product.name} – ${formatPrice(product.price)}`);console.log(available);This prints:
[ 'Cushion – £15.00', 'Desk lamp – £34.99', 'Side table – £45.00', 'Bookcase – £129.00']toSorted() arrived in ES2023. The older sort() does the same job but reorders the original array, which can surprise other code that uses it, so it is safer to call sort() only on an array the code has just created, such as the result of filter().
Totals with reduce
Section titled “Totals with reduce”reduce() combines every item into a single value, such as a total, by passing a running result from one call to the next. The second argument is the starting value.
const stockValue = products.reduce((sum, product) => sum + product.price * product.stock, 0);console.log(formatPrice(stockValue));This prints:
£1721.88Grouping, finding and checking
Section titled “Grouping, finding and checking”Object.groupBy(), added in ES2024, sorts items into groups by a key and returns an object with one array per group. find() returns the first item that matches, or undefined when none does, and some() and every() answer whether any or all of the items pass a test.
const byCategory = Object.groupBy(products, (product) => product.category);console.log(Object.keys(byCategory), byCategory.furniture.length);
console.log(products.find((product) => product.id === 'p4').name);console.log(products.some((product) => product.stock === 0));console.log(products.every((product) => product.price < 20000));This prints:
[ 'lighting', 'furniture', 'textiles' ] 2Side tabletruetrueA page might use groupBy() to show a heading for each category, find() to open one product’s details, and some() to decide whether to show an out of stock notice.
Building the page
Section titled “Building the page”In the browser, the last map() usually produces elements rather than strings. This snippet shows the products as a list, with a checkbox that hides the ones out of stock and a line underneath with the total of what is shown.
<label><input type="checkbox" id="in-stock-only"> Only show items in stock</label><ul id="product-list"></ul><p id="product-total"></p>const products = [ { id: 'p1', name: 'Desk lamp', category: 'lighting', price: 3499, stock: 12 }, { id: 'p2', name: 'Floor lamp', category: 'lighting', price: 8900, stock: 0 }, { id: 'p3', name: 'Bookcase', category: 'furniture', price: 12900, stock: 3 }, { id: 'p4', name: 'Side table', category: 'furniture', price: 4500, stock: 7 }, { id: 'p5', name: 'Cushion', category: 'textiles', price: 1500, stock: 40 },];
const formatPrice = (pence) => `£${(pence / 100).toFixed(2)}`;const checkbox = document.getElementById('in-stock-only');const list = document.getElementById('product-list');const total = document.getElementById('product-total');
const render = () => { const shown = products .filter((product) => !checkbox.checked || product.stock > 0) .toSorted((a, b) => a.name.localeCompare(b.name));
const items = shown.map((product) => { const item = document.createElement('li'); item.textContent = `${product.name}, ${formatPrice(product.price)}`; if (product.stock === 0) { item.textContent += ' (out of stock)'; item.style.color = 'grey'; } return item; }); list.replaceChildren(...items);
const sum = shown.reduce((runningTotal, product) => runningTotal + product.price, 0); total.textContent = `${shown.length} products, ${formatPrice(sum)} for one of each`;};
checkbox.addEventListener('change', render);render();The page first lists all five products in alphabetical order, with the floor lamp greyed out and marked (out of stock), and the line underneath reads 5 products, £312.99 for one of each. Ticking the box removes the floor lamp and changes the line to 4 products, £223.99 for one of each, and unticking it brings the lamp back.
replaceChildren() swaps the whole list in one operation, so the browser updates the page once rather than once per item. Building the elements with createElement() and textContent, rather than joining strings into innerHTML, also means that a product name containing < or & is shown as text and never treated as HTML.
The Array Filter Method, Array Map Method and Array Reduce Method pages cover each method on its own.
Steve Griffith covers this topic in his video Real World Array Method Uses in JavaScript Web Development.