• 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:

  • Replace a portion of a string with something else
  • Using the spread operator
  • Detect If an Element has focus
  • Insert an HTML string after the end of the specified element

Primary Sidebar

FREE UPDATES!

Get the latest updates in your inbox for FREE!

Popular Posts

Story Generator

IP Grabber – get a users IP address with JavaScript

Simple Calendar

Remove Ads

Astrological Calculator

Copyright © 2023 JavaScriptSource.com

  • About
  • Privacy Policy
  • Submit
  • FAQ
  • Jobs For Developers
  • Contact Us