Simple Guide to the Reduce Method in JavaScript Arrays

The reduce() method in JavaScript is a powerful tool that processes an array to produce a single output value. It iterates over each element, applying a function that combines them into one result, making it ideal for tasks like summing numbers, concatenating strings, or building objects. It doesn't modify the original array.


Syntax

Here's the basic syntax for reduce():

const result = array.reduce(function(accumulator, element, index, array) {
  // Return the updated accumulator
}, initialValue);
  • accumulator: The accumulated result (starts with initialValue or the first element).
  • element: The current item in the array (required).
  • index: The position of the item (optional, used in some examples).
  • array: The original array (rarely used, but available).
  • initialValue: Optional starting value for the accumulator (if omitted, the first element is used).

The reduce() method returns a single value after processing all elements.


Example 1: Sum of numbers

const numbers = [10, 20, 30];
const sum = numbers.reduce((acc, num) => acc + num, 0);
console.log(sum);

Output: 60


Example 2: Concatenate dish names

const dishes = ['idli', 'dosa', 'vada'];
const dishString = dishes.reduce((acc, dish) => acc + ', ' + dish, '');
console.log(dishString);

Output: ", idli, dosa, vada"


Example 3: Count total characters in names

const names = ['Arjun', 'Priya'];
const totalChars = names.reduce((acc, name) => acc + name.length, 0);
console.log(totalChars);

Output: 10


Example 4: Build a sentence from cities

const cities = ['Chennai', 'Bangalore'];
const sentence = cities.reduce((acc, city) => acc + ' and ' + city, 'Visit');
console.log(sentence);

Output: "Visit and Chennai and Bangalore"


Example 5: Find maximum age

const ages = [25, 30, 20];
const maxAge = ages.reduce((acc, age) => Math.max(acc, age), 0);
console.log(maxAge);

Output: 30


Example 6: Join foods with hyphen

const foods = ['sambar', 'rasam'];
const hyphenated = foods.reduce((acc, food) => acc + '-' + food, '');
console.log(hyphenated);

Output: "-sambar-rasam"


Example 7: Count occurrences of 'a' in dishes

const dishes = ['idli', 'dosa'];
const aCount = dishes.reduce((acc, dish) => acc + (dish.includes('a') ? 1 : 0), 0);
console.log(aCount);

Output: 1


Example 8: Create object from names

const names = ['Surya', 'Lakshmi'];
const nameObj = names.reduce((acc, name, i) => ({ ...acc, [i]: name }), {});
console.log(nameObj);

Output: {0: "Surya", 1: "Lakshmi"}


Example 9: Sum of even numbers

const nums = [1, 2, 3, 4];
const evenSum = nums.reduce((acc, num) => num % 2 === 0 ? acc + num : acc, 0);
console.log(evenSum);

Output: 6


Example 10: Combine greetings

const greetings = ['Hello', 'Vanakkam'];
const combined = greetings.reduce((acc, greet) => acc + ' ' + greet, '');
console.log(combined);

Output: " Hello Vanakkam"


Example 11: Find longest city name

const cities = ['Chennai', 'Kochi'];
const longest = cities.reduce((acc, city) => city.length > acc.length ? city : acc, '');
console.log(longest);

Output: "Chennai"


Example 12: Count true booleans

const bools = [true, false, true];
const trueCount = bools.reduce((acc, b) => acc + (b ? 1 : 0), 0);
console.log(trueCount);

Output: 2


Example 13: Create string from festivals

const festivals = ['Pongal', 'Onam'];
const festString = festivals.reduce((acc, fest) => acc + ', ' + fest, 'Festivals:');
console.log(festString);

Output: "Festivals:, Pongal, Onam"


Example 14: Sum ages from objects

const people = [{name: 'Raj', age: 30}, {name: 'Meena', age: 25}];
const totalAge = people.reduce((acc, p) => acc + p.age, 0);
console.log(totalAge);

Output: 55


Example 15: Find minimum score

const scores = [80, 70, 90];
const minScore = scores.reduce((acc, score) => Math.min(acc, score), Infinity);
console.log(minScore);

Output: 70


Example 16: Concatenate languages

const langs = ['Tamil', 'Telugu'];
const langString = langs.reduce((acc, lang) => acc + '/' + lang, '');
console.log(langString);

Output: "/Tamil/Telugu"


Example 17: Build array of first letters

const cities = ['Madurai', 'Ooty'];
const firstLetters = cities.reduce((acc, city) => [...acc, city[0]], []);
console.log(firstLetters);

Output: ["M", "O"]


Example 18: Count names longer than 4

const names = ['Anu', 'Lakshmi', 'Vijay'];
const longNameCount = names.reduce((acc, name) => acc + (name.length > 4 ? 1 : 0), 0);
console.log(longNameCount);

Output: 2


Example 19: Combine dishes into object

const dishes = ['idli', 'dosa'];
const dishObj = dishes.reduce((acc, dish) => ({ ...acc, [dish]: true }), {});
console.log(dishObj

Output: {idli: true, dosa: true}


Example 20: Sum numbers greater than 10

const nums = [5, 15, 20];
const bigSum = nums.reduce((acc, num) => num > 10 ? acc + num : acc, 0);
console.log(bigSum);

Output: 35


Example 21: Create numbered list string

const items = ['rice', 'dal'];
const numberedList = items.reduce((acc, item, i) => acc + `${i + 1}. ${item}, `, '');
console.log(numberedList);

Output: "1. rice, 2. dal, "


Example 22: Count cities starting with 'C'

const cities = ['Chennai', 'Madurai', 'Coimbatore'];
const cCount = cities.reduce((acc, city) => acc + (city.startsWith('C') ? 1 : 0), 0);
console.log(cCount);

Output: 2


Example 23: Join sweets with semicolon

const sweets = ['laddu', 'jalebi'];
const sweetString = sweets.reduce((acc, sweet) => acc + ';' + sweet, '');
console.log(sweetString);

Output: ";laddu;jalebi"


Example 24: Find shortest name

const names = ['Ram', 'Sita', 'Anu'];
const shortest = names.reduce((acc, name) => name.length < acc.length ? name : acc, names[0]);
console.log(shortest);

Output: "Ram"

Example 25: Sum lengths of festivals

const festivals = ['Pongal', 'Onam'];
const totalLength = festivals.reduce((acc, fest) => acc + fest.length, 0);
console.log(totalLength);

Output: 9


Example 26: Create array of ages

const people = [{name: 'Anu', age: 22}, {name: 'Vikram', age: 28}];
const agesArray = people.reduce((acc, p) => [...acc, p.age], []);
console.log(agesArray);

Output: [22, 28]


Example 27: Count dishes with 'a'

const dishes = ['sambar', 'idli', 'rasam'];
const aDishCount = dishes.reduce((acc, dish) => acc + (dish.includes('a') ? 1 : 0), 0);
console.log(aDishCount);

Output: 2


Example 28: Combine cities into object

const cities = ['Trichy', 'Salem'];
const cityObj = cities.reduce((acc, city, i) => ({ ...acc, [city]: i }), {});
console.log(cityObj);

Output: {Trichy: 0, Salem: 1}


Example 29: Sum odd numbers

const nums = [1, 2, 3, 4];
const oddSum = nums.reduce((acc, num) => num % 2 !== 0 ? acc + num : acc, 0);
console.log(oddSum);

Output: 4


Example 30: Create greeting string

const names = ['Karthik', 'Sowmya'];
const greeting = names.reduce((acc, name) => acc + 'Hi ' + name + ', ', '');
console.log(greeting);

Output: "Hi Karthik, Hi Sowmya, "


Example 31: Count scores above 75

const scores = [70, 80, 90];
const highScoreCount = scores.reduce((acc, score) => acc + (score > 75 ? 1 : 0), 0);
console.log(highScoreCount);

Output: 2


Example 32: Build array of last letters

const dishes = ['idli', 'dosa'];
const lastLetters = dishes.reduce((acc, dish) => [...acc, dish[dish.length - 1]], []);
console.log(lastLetters);

Output: ["i", "a"]


Example 33: Concatenate dance names

const dances = ['Bharatanatyam', 'Kuchipudi'];
const danceString = dances.reduce((acc, dance) => acc + ', ' + dance, 'Dances:');
console.log(danceString);

Output: "Dances:, Bharatanatyam, Kuchipudi"


Example 34: Find longest festival name

const festivals = ['Pongal', 'Diwali'];
const longestFest = festivals.reduce((acc, fest) => fest.length > acc.length ? fest : acc, '');
console.log(longestFest);

Output: "Pongal"


Example 35: Sum ages less than 30

const ages = [25, 35, 28];
const youngSum = ages.reduce((acc, age) => age < 30 ? acc + age : acc, 0);
console.log(youngSum);

Output: 53


Example 36: Create object from sweets

const sweets = ['laddu', 'jalebi'];
const sweetObj = sweets.reduce((acc, sweet) => ({ ...acc, [sweet]: sweet.length }), {});
console.log(sweetObj);

Output: {laddu: 5, jalebi: 6}


Example 37: Count names starting with 'S'

const names = ['Surya', 'Arun', 'Sita'];
const sCount = names.reduce((acc, name) => acc + (name.startsWith('S') ? 1 : 0), 0);
console.log(sCount);

Output: 2


Example 38: Join temples with space

const temples = ['Madurai', 'Tirupati'];
const templeString = temples.reduce((acc, temple) => acc + ' ' + temple, '');
console.log(templeString);

Output: " Madurai Tirupati"


Example 39: Sum lengths of words with 'a'

const words = ['Tamil', 'Nadu', 'Telugu'];
const aLengthSum = words.reduce((acc, word) => word.includes('a') ? acc + word.length : acc, 0);
console.log(aLengthSum);

Output: 10


Example 40: Find shortest city

const cities = ['Ooty', 'Chennai', 'Mysore'];
const shortestCity = cities.reduce((acc, city) => city.length < acc.length ? city : acc, cities[0]);
console.log(shortestCity);

Output: "Ooty"


Example 41: Create array of names

const people = [{name: 'Anita', age: 25}, {name: 'Vijay', age: 30}];
const nameArray = people.reduce((acc, p) => [...acc, p.name], []);
console.log(nameArray);

Output: ["Anita", "Vijay"]


Example 42: Count dishes ending with 'a'

const dishes = ['idli', 'dosa', 'vada'];
const aEndingCount = dishes.reduce((acc, dish) => acc + (dish.endsWith('a') ? 1 : 0), 0);
console.log(aEndingCount);

Output: 2


Example 43: Combine fruits into string

const fruits = ['mango', 'banana'];
const fruitString = fruits.reduce((acc, fruit) => acc + ', ' + fruit, 'Fruits:');
console.log(fruitString);

Output: "Fruits:, mango, banana"


Example 44: Sum scores below 85

const scores = [80, 90, 75];
const lowScoreSum = scores.reduce((acc, score) => score < 85 ? acc + score : acc, 0);
console.log(lowScoreSum);

Output: 155


Example 45: Create object from curries

const curries = ['sambar', 'rasam'];
const curryObj = curries.reduce((acc, curry, i) => ({ ...acc, [curry]: i + 1 }), {});
console.log(curryObj);

Output: {sambar: 1, rasam: 2}


Example 46: Count even numbers

const nums = [1, 2, 3, 4];
const evenCount = nums.reduce((acc, num) => acc + (num % 2 === 0 ? 1 : 0), 0);
console.log(evenCount);

Output: 2


Example 47: Join places with comma

const places = ['Kerala', 'Goa'];
const placeString = places.reduce((acc, place) => acc + ', ' + place, '');
console.log(placeString);

Output: ", Kerala, Goa"


Example 48: Find longest name

const names = ['Ram', 'Lakshmi', 'Anu'];
const longestName = names.reduce((acc, name) => name.length > acc.length ? name : acc, names[0]);
console.log(longestName);

Output: "Lakshmi"


Example 49: Sum lengths of dances

const dances = ['Bharatanatyam', 'Kuchipudi'];
const danceLengthSum = dances.reduce((acc, dance) => acc + dance.length, 0);
console.log(danceLengthSum);

Output: 22


Example 50: Create array of indexed items

const items = ['rice', 'dal'];
const indexedItems = items.reduce((acc, item, i) => [...acc, `${i}: ${item}`], []);
console.log(indexedItems);

Output: ["0: rice", "1: dal"]


List of Programs


JavaScript Arrays & Methods Examples


JS Practical Project