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.
Here's the basic syntax for reduce():
const result = array.reduce(function(accumulator, element, index, array) { // Return the updated accumulator }, initialValue);
The reduce() method returns a single value after processing all elements.
const numbers = [10, 20, 30]; const sum = numbers.reduce((acc, num) => acc + num, 0); console.log(sum);
Output: 60
const dishes = ['idli', 'dosa', 'vada']; const dishString = dishes.reduce((acc, dish) => acc + ', ' + dish, ''); console.log(dishString);
Output: ", idli, dosa, vada"
const names = ['Arjun', 'Priya']; const totalChars = names.reduce((acc, name) => acc + name.length, 0); console.log(totalChars);
Output: 10
const cities = ['Chennai', 'Bangalore']; const sentence = cities.reduce((acc, city) => acc + ' and ' + city, 'Visit'); console.log(sentence);
Output: "Visit and Chennai and Bangalore"
const ages = [25, 30, 20]; const maxAge = ages.reduce((acc, age) => Math.max(acc, age), 0); console.log(maxAge);
Output: 30
const foods = ['sambar', 'rasam']; const hyphenated = foods.reduce((acc, food) => acc + '-' + food, ''); console.log(hyphenated);
Output: "-sambar-rasam"
const dishes = ['idli', 'dosa']; const aCount = dishes.reduce((acc, dish) => acc + (dish.includes('a') ? 1 : 0), 0); console.log(aCount);
Output: 1
const names = ['Surya', 'Lakshmi']; const nameObj = names.reduce((acc, name, i) => ({ ...acc, [i]: name }), {}); console.log(nameObj);
Output: {0: "Surya", 1: "Lakshmi"}
const nums = [1, 2, 3, 4]; const evenSum = nums.reduce((acc, num) => num % 2 === 0 ? acc + num : acc, 0); console.log(evenSum);
Output: 6
const greetings = ['Hello', 'Vanakkam']; const combined = greetings.reduce((acc, greet) => acc + ' ' + greet, ''); console.log(combined);
Output: " Hello Vanakkam"
const cities = ['Chennai', 'Kochi']; const longest = cities.reduce((acc, city) => city.length > acc.length ? city : acc, ''); console.log(longest);
Output: "Chennai"
const bools = [true, false, true]; const trueCount = bools.reduce((acc, b) => acc + (b ? 1 : 0), 0); console.log(trueCount);
Output: 2
const festivals = ['Pongal', 'Onam']; const festString = festivals.reduce((acc, fest) => acc + ', ' + fest, 'Festivals:'); console.log(festString);
Output: "Festivals:, Pongal, Onam"
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
const scores = [80, 70, 90]; const minScore = scores.reduce((acc, score) => Math.min(acc, score), Infinity); console.log(minScore);
Output: 70
const langs = ['Tamil', 'Telugu']; const langString = langs.reduce((acc, lang) => acc + '/' + lang, ''); console.log(langString);
Output: "/Tamil/Telugu"
const cities = ['Madurai', 'Ooty']; const firstLetters = cities.reduce((acc, city) => [...acc, city[0]], []); console.log(firstLetters);
Output: ["M", "O"]
const names = ['Anu', 'Lakshmi', 'Vijay']; const longNameCount = names.reduce((acc, name) => acc + (name.length > 4 ? 1 : 0), 0); console.log(longNameCount);
Output: 2
const dishes = ['idli', 'dosa']; const dishObj = dishes.reduce((acc, dish) => ({ ...acc, [dish]: true }), {}); console.log(dishObj
Output: {idli: true, dosa: true}
const nums = [5, 15, 20]; const bigSum = nums.reduce((acc, num) => num > 10 ? acc + num : acc, 0); console.log(bigSum);
Output: 35
const items = ['rice', 'dal']; const numberedList = items.reduce((acc, item, i) => acc + `${i + 1}. ${item}, `, ''); console.log(numberedList);
Output: "1. rice, 2. dal, "
const cities = ['Chennai', 'Madurai', 'Coimbatore']; const cCount = cities.reduce((acc, city) => acc + (city.startsWith('C') ? 1 : 0), 0); console.log(cCount);
Output: 2
const sweets = ['laddu', 'jalebi']; const sweetString = sweets.reduce((acc, sweet) => acc + ';' + sweet, ''); console.log(sweetString);
Output: ";laddu;jalebi"
const names = ['Ram', 'Sita', 'Anu']; const shortest = names.reduce((acc, name) => name.length < acc.length ? name : acc, names[0]); console.log(shortest);
Output: "Ram"
const festivals = ['Pongal', 'Onam']; const totalLength = festivals.reduce((acc, fest) => acc + fest.length, 0); console.log(totalLength);
Output: 9
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]
const dishes = ['sambar', 'idli', 'rasam']; const aDishCount = dishes.reduce((acc, dish) => acc + (dish.includes('a') ? 1 : 0), 0); console.log(aDishCount);
Output: 2
const cities = ['Trichy', 'Salem']; const cityObj = cities.reduce((acc, city, i) => ({ ...acc, [city]: i }), {}); console.log(cityObj);
Output: {Trichy: 0, Salem: 1}
const nums = [1, 2, 3, 4]; const oddSum = nums.reduce((acc, num) => num % 2 !== 0 ? acc + num : acc, 0); console.log(oddSum);
Output: 4
const names = ['Karthik', 'Sowmya']; const greeting = names.reduce((acc, name) => acc + 'Hi ' + name + ', ', ''); console.log(greeting);
Output: "Hi Karthik, Hi Sowmya, "
const scores = [70, 80, 90]; const highScoreCount = scores.reduce((acc, score) => acc + (score > 75 ? 1 : 0), 0); console.log(highScoreCount);
Output: 2
const dishes = ['idli', 'dosa']; const lastLetters = dishes.reduce((acc, dish) => [...acc, dish[dish.length - 1]], []); console.log(lastLetters);
Output: ["i", "a"]
const dances = ['Bharatanatyam', 'Kuchipudi']; const danceString = dances.reduce((acc, dance) => acc + ', ' + dance, 'Dances:'); console.log(danceString);
Output: "Dances:, Bharatanatyam, Kuchipudi"
const festivals = ['Pongal', 'Diwali']; const longestFest = festivals.reduce((acc, fest) => fest.length > acc.length ? fest : acc, ''); console.log(longestFest);
Output: "Pongal"
const ages = [25, 35, 28]; const youngSum = ages.reduce((acc, age) => age < 30 ? acc + age : acc, 0); console.log(youngSum);
Output: 53
const sweets = ['laddu', 'jalebi']; const sweetObj = sweets.reduce((acc, sweet) => ({ ...acc, [sweet]: sweet.length }), {}); console.log(sweetObj);
Output: {laddu: 5, jalebi: 6}
const names = ['Surya', 'Arun', 'Sita']; const sCount = names.reduce((acc, name) => acc + (name.startsWith('S') ? 1 : 0), 0); console.log(sCount);
Output: 2
const temples = ['Madurai', 'Tirupati']; const templeString = temples.reduce((acc, temple) => acc + ' ' + temple, ''); console.log(templeString);
Output: " Madurai Tirupati"
const words = ['Tamil', 'Nadu', 'Telugu']; const aLengthSum = words.reduce((acc, word) => word.includes('a') ? acc + word.length : acc, 0); console.log(aLengthSum);
Output: 10
const cities = ['Ooty', 'Chennai', 'Mysore']; const shortestCity = cities.reduce((acc, city) => city.length < acc.length ? city : acc, cities[0]); console.log(shortestCity);
Output: "Ooty"
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"]
const dishes = ['idli', 'dosa', 'vada']; const aEndingCount = dishes.reduce((acc, dish) => acc + (dish.endsWith('a') ? 1 : 0), 0); console.log(aEndingCount);
Output: 2
const fruits = ['mango', 'banana']; const fruitString = fruits.reduce((acc, fruit) => acc + ', ' + fruit, 'Fruits:'); console.log(fruitString);
Output: "Fruits:, mango, banana"
const scores = [80, 90, 75]; const lowScoreSum = scores.reduce((acc, score) => score < 85 ? acc + score : acc, 0); console.log(lowScoreSum);
Output: 155
const curries = ['sambar', 'rasam']; const curryObj = curries.reduce((acc, curry, i) => ({ ...acc, [curry]: i + 1 }), {}); console.log(curryObj);
Output: {sambar: 1, rasam: 2}
const nums = [1, 2, 3, 4]; const evenCount = nums.reduce((acc, num) => acc + (num % 2 === 0 ? 1 : 0), 0); console.log(evenCount);
Output: 2
const places = ['Kerala', 'Goa']; const placeString = places.reduce((acc, place) => acc + ', ' + place, ''); console.log(placeString);
Output: ", Kerala, Goa"
const names = ['Ram', 'Lakshmi', 'Anu']; const longestName = names.reduce((acc, name) => name.length > acc.length ? name : acc, names[0]); console.log(longestName);
Output: "Lakshmi"
const dances = ['Bharatanatyam', 'Kuchipudi']; const danceLengthSum = dances.reduce((acc, dance) => acc + dance.length, 0); console.log(danceLengthSum);
Output: 22
const items = ['rice', 'dal']; const indexedItems = items.reduce((acc, item, i) => [...acc, `${i}: ${item}`], []); console.log(indexedItems);
Output: ["0: rice", "1: dal"]
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions