• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
JavaScriptSource

JavaScriptSource

Search 5,000+ Free JavaScript Snippets

  • Home
  • Browse Snippets
    • Addon
    • Ajax
    • Buttons
    • Cookies
    • CSS
    • Featured
    • Forms
    • Games
    • Generators
    • Image Effects
    • Math Related
    • Miscellaneous
    • Multimedia
    • Navigation
    • Page Details
    • Passwords
    • Text Effects
    • Time & Date
    • User Details
Home / Miscellaneous / Take the content of an array and return a single value

Take the content of an array and return a single value

Take the content of an array and return a single value.

Take the content of an array and return a single value. That value can be anything: a string, number, object, or even another array.

The Array.reduce() method accepts two arguments: a callback method to run against each item in the array, and a starting value.

The callback also accepts two arguments: the accumulator, which is the current combined value, and the current item in the loop. Whatever you return is used as the accumulator for the next item in the loop. On the very first loop, that starting value is used instead.

/**
 * Add all of the numbers in an array
 */

var total = [1, 2, 3].reduce(function (sum, current) {
	return sum + current;
}, 0);

// logs 6
console.log(total);


/**
 * Create a new array with only the names of wizards in Huffepuff
 */

var wizards = [
	{
		name: 'Harry Potter',
		house: 'Gryfindor'
	},
	{
		name: 'Cedric Diggory',
		house: 'Hufflepuff'
	},
	{
		name: 'Tonks',
		house: 'Hufflepuff'
	},
	{
		name: 'Ronald Weasley',
		house: 'Gryfindor'
	},
	{
		name: 'Hermione Granger',
		house: 'Gryfindor'
	}
];

// This combines what you would otherwise do with map() and filter() into one step
var hufflepuff = wizards.reduce(function (newArr, wizard) {
	if (wizard.house === 'Hufflepuff') {
		newArr.push(wizard.name);
	}
	return newArr;
}, []);

// logs ["Cedric Diggory", "Tonks"]
console.log(hufflepuff);

Source

https://vanillajstoolkit.com/reference/arrays/array-reduce/

Miscellaneous

Related Snippets:

  • How To Replace All Occurrences of a String in JavaScript
  • Find a Specific Element from an Array
  • 3 Ways To Find an Object by ID in a JavaScript Array
  • Create a one time event handler

Primary Sidebar

Popular Posts

Story Generator

IP Grabber – get a users IP address with JavaScript

Simple Calendar

Remove Ads

Astrological Calculator

Copyright © 2025 JavaScriptSource.com

  • About
  • Privacy Policy
  • FAQ
  • Jobs For Developers