Programming fundamentals · Beginner · 18 min
Work with arrays in JavaScript: map, filter and reduce
By Padding · Updated 18 Nov 2026
Node.js 26.13.1 LTS · node:26 image
You will turn a list of shop products into prices with tax, in-stock lists, yes-or-no answers, totals and a sorted stock report, using map, filter, find, some, every, reduce and toSorted in Node.js 26.
On this page
An array is an ordered list of values. Most data a program handles arrives as one: the rows of a spreadsheet, the messages in a chat, the products in a shop. Sooner or later you need to change every item, keep only some of them, find one, or add them up.
You can do all of that with a for loop. JavaScript arrays also have methods that each do one of those jobs, and code written with them says what it does in a single line. In this tutorial you write a few loops first, then replace them with map, filter, find, some, every and reduce, sort with a compare function, and finish with a short stock report that chains several methods together.
The running example is a small shop's product list: each product has a name, a price and a number in stock. Read the prices in your own currency. Commands are shown for a Linux or macOS shell; on Windows, PowerShell runs the node commands the same way. Nothing is downloaded beyond Node.js itself.
Step 1 · Set up the project and the product list
Check your Node.js version, then make a folder for this tutorial with a package.json and a file that holds the products:
node --version
mkdir -p ~/arrays-demo
cd ~/arrays-demo
cat > package.json <<'JSON'
{
"name": "arrays-demo",
"private": true,
"type": "module"
}
JSON
cat > products.js <<'JS'
export const products = [
{ name: "Rice 5kg", price: 12.5, stock: 8 },
{ name: "Cooking oil 1L", price: 4.2, stock: 0 },
{ name: "Tomato paste", price: 1.1, stock: 40 },
{ name: "Tea bags", price: 3.75, stock: 15 },
{ name: "Sugar 1kg", price: 2.4, stock: 0 },
];
JS"type": "module" in package.json lets every .js file in the folder use import and export. That way each script in this tutorial can load the same product list instead of repeating it.
In products.js, the square brackets [ ... ] make an array, and each item inside it is an object written with curly braces. An object groups named values: name, price and stock. export const products gives the array a name and makes it available to other files. Two of the five products have a stock of 0, which matters later.
Check it worked
node --version prints v26. followed by the rest of the version number, for example v26.13.1. Run ls in ~/arrays-demo and you see package.json and products.js. If the version starts with a lower number, install Node.js 26 before you continue: the toSorted method in a later step needs Node.js 20 or newer.
Step 2 · Loop over the products with for...of
Start with the tool you may already know. Create loop.js, which prints every product and then builds a list of the ones in stock:
cat > loop.js <<'JS'
import { products } from "./products.js";
console.log(products.length, "products");
for (const product of products) {
console.log(product.name, product.price);
}
const inStock = [];
for (const product of products) {
if (product.stock > 0) {
inStock.push(product.name);
}
}
console.log(inStock);
JS
node loop.jsLine by line:
import { products } from "./products.js";loads the array you exported. The./means "in this folder".products.lengthis the number of items in the array.for (const product of products)runs the block once per item. On each pass,productis the current object, soproduct.nameis that product's name.const inStock = [];creates an empty array.inStock.push(product.name)adds a value to the end ofinStock. Note thatpushchanges the array it is called on. Keep that in mind for the sorting step.
The second loop has a pattern you will see everywhere: make an empty array, loop, test each item, push the ones you want. The rest of this tutorial replaces patterns like that with one method call each.
Check it worked
The output starts with 5 products, then five lines such as Rice 5kg 12.5 and Cooking oil 1L 4.2, and ends with:
[ 'Rice 5kg', 'Tomato paste', 'Tea bags' ]The cooking oil and the sugar are missing from the last line because their stock is 0.
Step 3 · Change every item with map
map calls a function once for each item and collects what the function returns into a new array of the same length. The function you pass in is called a callback: you hand it over, and map calls it for you.
Create map.js. It makes a list of names, then a list of prices with a 7.5% sales tax added:
cat > map.js <<'JS'
import { products } from "./products.js";
const TAX_RATE = 0.075;
const names = products.map((product) => product.name);
console.log(names);
const withTax = products.map((product) => {
const total = product.price * (1 + TAX_RATE);
return { name: product.name, priceWithTax: Number(total.toFixed(2)) };
});
console.log(withTax);
console.log(products[0]);
JS
node map.jsThe callbacks are arrow functions. (product) => product.name is a function that takes one value, calls it product, and returns product.name. When the body is a single expression after the arrow, its value is returned without the word return.
The second callback needs two lines, so its body is wrapped in curly braces, and then you must write return yourself. Inside it:
product.price * (1 + TAX_RATE)is the price plus 7.5%.total.toFixed(2)rounds to two decimal places but gives back text, such as"13.44".Number(...)turns that text back into a number.{ name: ..., priceWithTax: ... }builds a new object for the new array.
The last line prints the first product from the original array, which you can read as products[0]: positions in an array start at 0.
Check it worked
You see the five names in an array, then five objects such as { name: 'Rice 5kg', priceWithTax: 13.44 } and { name: 'Tomato paste', priceWithTax: 1.18 }. The last line is { name: 'Rice 5kg', price: 12.5, stock: 8 }: the original product still has its old price and no tax field. map built a new array and left products alone.
A common mistake: writing (product) => { product.name } with curly braces but no return. The braces make it a block, the block returns nothing, and you get an array full of undefined.
Step 4 · Keep some items with filter and find one with find
filter also calls your function once per item, but the function answers a question with true or false. Items that get true go into a new array; the rest are left out. find asks the same kind of question and stops at the first item that answers true, returning that item itself rather than an array.
Create filter.js:
cat > filter.js <<'JS'
import { products } from "./products.js";
const available = products.filter((product) => product.stock > 0);
console.log(available.map((product) => product.name));
const cheap = products.filter((product) => product.price < 3);
console.log(cheap.length, "cheap products");
const tea = products.find((product) => product.name === "Tea bags");
console.log(tea);
const coffee = products.find((product) => product.name === "Coffee");
console.log(coffee);
JS
node filter.jsThe first two lines do the same job as the second loop in loop.js, in one line: keep the products whose stock is above zero, then map them to their names. Calling one method on the result of another like this is called chaining.
=== checks that two values are equal and of the same type. Use it rather than ==, which converts types first and can give surprising answers.
Check it worked
The output is:
[ 'Rice 5kg', 'Tomato paste', 'Tea bags' ]
2 cheap products
{ name: 'Tea bags', price: 3.75, stock: 15 }
undefinedThe first line matches the loop version exactly. Two products cost less than 3: the tomato paste and the sugar. find returned the tea object, and returned undefined for coffee because no product has that name. Before you use what find gives you, check that it is not undefined, or reading coffee.price stops your program with a TypeError.
Step 5 · Ask yes-or-no questions with some and every
Sometimes you do not need the matching items, only an answer. some returns true if at least one item passes your test. every returns true only if all of them do. Both stop looking as soon as they know the answer.
Create checks.js:
cat > checks.js <<'JS'
import { products } from "./products.js";
const anySoldOut = products.some((product) => product.stock === 0);
const allPriced = products.every((product) => product.price > 0);
const allInStock = products.every((product) => product.stock > 0);
console.log("Any sold out?", anySoldOut);
console.log("All priced?", allPriced);
console.log("All in stock?", allInStock);
JS
node checks.jsA shop could use anySoldOut to decide whether to show a "restock needed" warning, and allPriced to refuse to publish a price list that has a missing price.
Check it worked
The output is Any sold out? true, All priced? true and All in stock? false. Change the cooking oil's and the sugar's stock in products.js to 3, run node checks.js again, and the first and last answers flip. Put both back to 0 before you continue, because later output in this tutorial assumes them.
Step 6 · Combine every item into one value with reduce
reduce walks through the array carrying a running result, often called the accumulator. Your callback receives the result so far and the current item, and returns the new result. The second argument to reduce is where the result starts.
Create reduce.js, which counts the units in the shop and works out what the stock is worth:
cat > reduce.js <<'JS'
import { products } from "./products.js";
const unitsInStore = products.reduce((sum, product) => sum + product.stock, 0);
console.log("Units:", unitsInStore);
const stockValue = products.reduce(
(sum, product) => sum + product.price * product.stock,
0,
);
console.log("Stock value:", stockValue.toFixed(2));
const empty = [];
console.log("Empty total:", empty.reduce((sum, n) => sum + n, 0));
JS
node reduce.jsFollow the first reduce by hand. sum starts at 0. The rice adds 8, giving 8. The oil adds 0, still 8. The tomato paste adds 40, giving 48. The tea adds 15, giving 63. The sugar adds 0. The final sum, 63, is what reduce returns.
The second reduce multiplies each price by its stock before adding, so it gives the total value of everything on the shelves.
Always pass the starting value. The last line shows why: with 0 as the start, an empty array gives 0. Without it, [].reduce((sum, n) => sum + n) stops your program with TypeError: Reduce of empty array with no initial value, which is easy to miss when your test data always has items in it.
Check it worked
The output is Units: 63, Stock value: 200.25 and Empty total: 0. Check the value with a calculator: 12.5 × 8 + 1.1 × 40 + 3.75 × 15 = 100 + 44 + 56.25 = 200.25.
Step 7 · Sort with a compare function and keep the original
Sorting has two surprises. Create sort.js to see both:
cat > sort.js <<'JS'
import { products } from "./products.js";
console.log([10, 9, 1].sort());
console.log([10, 9, 1].sort((a, b) => a - b));
const cheapestFirst = products.toSorted((a, b) => a.price - b.price);
console.log(cheapestFirst.map((product) => product.name));
console.log(products[0].name);
products.sort((a, b) => b.stock - a.stock);
console.log(products[0].name);
JS
node sort.jsThe first surprise: [10, 9, 1].sort() gives [ 1, 10, 9 ]. With no arguments, sort turns every item into text and orders the text the way a dictionary does. As text, "10" comes before "9" because "1" comes before "9".
To sort numbers, pass a compare function. sort calls it with two items, a and b, and looks only at whether the answer is negative, zero or positive:
- negative:
agoes first - positive:
bgoes first - zero: keep their order
a - b is negative when a is smaller, so it sorts from smallest to largest. b - a sorts from largest to smallest.
The second surprise: sort reorders the array you call it on, like push changes the array it adds to. map and filter never do that. If other code still needs the original order, use toSorted, which takes the same compare function and returns a sorted copy.
In the script, toSorted puts the cheapest products first, and products[0] is still the rice afterwards. Then products.sort sorts by stock, largest first, and changes products itself. The change lasts only while this script runs: the next node command loads products.js fresh.
Check it worked
The first two lines are [ 1, 10, 9 ] and [ 1, 9, 10 ]. Next comes the cheapest-first list, starting with 'Tomato paste' and ending with 'Rice 5kg'. The line after it is Rice 5kg, because toSorted left the original alone. The last line is Tomato paste: after sort, the product with the most stock, 40, sits at position 0 of the original array.
Step 8 · Build a stock report by chaining methods
Put the methods together in report.js. It keeps the products in stock, works out the value of each line with tax, sorts the most valuable first, prints a table and a total, and lists what has sold out:
cat > report.js <<'JS'
import { products } from "./products.js";
const TAX_RATE = 0.075;
const lines = products
.filter((product) => product.stock > 0)
.map((product) => ({
name: product.name,
value: product.price * (1 + TAX_RATE) * product.stock,
}))
.toSorted((a, b) => b.value - a.value);
for (const line of lines) {
console.log(line.name.padEnd(14), line.value.toFixed(2).padStart(8));
}
const total = lines.reduce((sum, line) => sum + line.value, 0);
console.log("Total".padEnd(14), total.toFixed(2).padStart(8));
const soldOut = products.filter((product) => product.stock === 0);
console.log("Sold out:", soldOut.map((product) => product.name).join(", "));
JS
node report.jsRead the chain from top to bottom, one step per line: start with products, keep the ones in stock, turn each into a { name, value } object, sort by value. Each method hands its new array to the next.
Two details in the code:
- In
.map((product) => ({ ... })), the object is wrapped in round brackets. Without them, JavaScript reads the curly braces as a function body, not an object, and the callback returnsundefined. padEnd(14)adds spaces after a name until it is 14 characters long, andpadStart(8)adds spaces before the number, so the columns line up.join(", ")turns an array of names into one string with a comma between each.
The for...of loop stays. It prints one line per item, which is a job for a loop, not for map: use map when you want a new array back.
If you sell in more than one language, product names may contain letters such as é or ọ. The array methods treat them like any other text, but some characters made of two parts are counted as two by padEnd, so a column may shift by a space. For a report on screen that is usually fine; for printed receipts, test with your real product names.
Check it worked
The output is:
Rice 5kg 107.50
Tea bags 60.47
Tomato paste 47.30
Total 215.27
Sold out: Cooking oil 1L, Sugar 1kgThe rice line is 12.5 × 1.075 × 8 = 107.50. The cooking oil and the sugar appear only in the sold-out line.
When you have finished, delete the demo folder:
cd ~
rm -rf ~/arrays-demoNext steps
- Use these methods in a real program: build a to-do list command-line app in Node stores its tasks in an array and filters and maps them.
- Learn how the
importandexportlines in this tutorial work: use JavaScript modules with import and export. - Revisit why
constarrays can still change withpushandsort: declare variables with let and const in JavaScript. - Compare with Python, where lists and loops play the same role: loop over lists, ranges and dictionaries with for.
Part of these paths
Related tutorials
- Declare variables with let and const in JavaScript, and understand its typesYou will declare variables with const and let in Node.js, see block scope and the seven primitive types for yourself, predict JavaScript's type coercion, and finish with a script that turns text input into numbers safely.
- Build a to-do list command-line app in Node.jsYou will build todo.js, a Node.js command-line app with add, list, done and remove commands that keeps your tasks in a JSON file, gives clear messages for mistakes and is covered by two passing tests.
- Loop over lists, ranges and dictionaries with forYou will use Python's for loop with range, enumerate, zip and dictionary items, fix an off-by-one error, skip and stop with continue and break, and finish with a script that prints a multiplication table and a class attendance report.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials