- Reduce array to a single string
- Reduce array to a single string
- Javascript Array reduce()
- reduce() Syntax
- reduce() Parameters
- reduce() Return Value
- Example 1: Sum of All Values of Array
- Example 2: Subtracting Numbers in Array
- Example 3: Remove Duplicate Items from Array
- Example 4: Grouping Objects by a property
- JavaScript Array reduce()
- Definition and Usage
Reduce array to a single string
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join IMPORTANT — if you’re array contains objects, then you might want to map it before joining: or, if you’re really fired up about using reduce, just make sure you use the previous value, current value and index when passing in the callback. Example reduce() Syntax The syntax of the method is: Here, arr is an array. reduce() Parameters The method takes in: callback — The function to execute on each array element (except the first element if no initialValue is provided).
Reduce array to a single string
I would like to use the reduce function instead of doing this:
var result = ''; authors.forEach( function(author) < result += author.name + ', '; >); console.log(result);
So in the array authors there are several names. Now I want to build a string with this names, separated by comma (except the last one).
var result = authors.reduce(function (author, index) < return author + ' '; >, ''); console.log(result);
A flurry of answers just came in and here is one more!
The first option is using the native js join method which eliminates the need for reduce. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join
var authors = ['some author', 'another author', 'last author']; var authorString = authors.join(","); console.log(authorString);
IMPORTANT — if you’re array contains objects, then you might want to map it before joining:
var authors = [,,] var authorString = authors.map(function(author)< return author.name; >).join(","); console.log(authorString);
or, if you’re really fired up about using reduce, just make sure you use the previous value, current value and index when passing in the callback. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
var authorString = authors.reduce(function(prevVal,currVal,idx)< return idx == 0 ? currVal : prevVal + ', ' + currVal; >, '') console.log(authorString);
IMPORTANT — again if your array contains objects then you will want to make sure you are using the ‘name property’:
var authors = [,,]; var authorString = authors.reduce(function(prevVal,currVal,idx)< return idx == 0 ? currVal.name : prevVal + ', ' + currVal.name; >, '') console.log(authorString);
Right, so it’s an object. Let’s map the names first then:
var result = authors.map(function( author ) < return author.name; >).join(', ');
var authors = ["a","b","c"]; var str = authors.join(", "); console.log(str);
if you want to use reduce add an if check
var authors = ["a","b","c"];var result = authors.reduce(function (author, val, index) < var comma = author.length ? ", " : ""; return author + comma + val; >, ''); console.log(result);
Since I missed the mapping part to make people happy.
var authors = [< name: "a" >, < name: "b" >, < name: "c" >];var res = authors.map( function(val) < return val.name; >).join(", "); console.log(res);
var authors = [< name: "a" >, < name: "b" >, < name: "c" >]; var result = authors.reduce(function(author, val, index) < var comma = author.length ? ", " : ""; return author + comma + val.name; >, ''); console.log(result);
I came across this also. Most of these answers dont take into account that you want the author s name, meaning you have an array of objects.
authors.reduce((prev, curr) => [. prev, curr.name], []).join(', ');
JavaScript Array isArray() Method, The Array.isArray () was released with the release of ECMAScript5 JavaScript. This method simply checks whether the argument passed to its arguments is an array or not. This article will explain this Array isArray () method by explaining its syntax and then showcasing some examples. We will start by going over the …
Javascript Array reduce()
In this tutorial, we will learn about the JavaScript Array reduce() method with the help of examples.
The reduce() method executes a reducer function on each element of the array and returns a single output value.
Example
const message = ["JavaScript ", "is ", "fun."]; // function to join each string elements function joinStrings(accumulator, currentValue) < return accumulator + currentValue; >// reduce join each element of the string let joinedString = message.reduce(joinStrings); console.log(joinedString); // Output: JavaScript is fun.
reduce() Syntax
The syntax of the reduce() method is:
arr.reduce(callback(accumulator, currentValue), initialValue)
reduce() Parameters
The reduce() method takes in:
- callback — The function to execute on each array element (except the first element if no initialValue is provided). It takes in
- accumulator — It accumulates the callback’s return values.
- currentValue — The current element being passed from the array.
Note: Calling reduce() on an empty array without initialValue will throw TypeError .
reduce() Return Value
- reduce() executes the given function for each value from left to right.
- reduce() does not change the original array.
- It is almost always safer to provide initialValue .
Example 1: Sum of All Values of Array
const numbers = [1, 2, 3, 4, 5, 6]; function sum_reducer(accumulator, currentValue) < return accumulator + currentValue; >
let sum = numbers.reduce(sum_reducer);console.log(sum); // 21// using arrow function let summation = numbers.reduce( (accumulator, currentValue) => accumulator + currentValue );console.log(summation); // 21Example 2: Subtracting Numbers in Array
const numbers = [1800, 50, 300, 20, 100]; // subtract all numbers from first number // since 1st element is called as accumulator rather than currentValue // 1800 - 50 - 300 - 20 - 100
let difference = numbers.reduce( (accumulator, currentValue) => accumulator - currentValue );console.log(difference); // 1330 const expenses = [1800, 2000, 3000, 5000, 500]; const salary = 15000; // function that subtracts all array elements from given number // 15000 - 1800 - 2000 - 3000 - 5000 - 500let remaining = expenses.reduce( (accumulator, currentValue) => accumulator - currentValue, salary );console.log(remaining); // 2700This example clearly explains the difference between passing an initialValue and not passing an initialValue .
Example 3: Remove Duplicate Items from Array
let ageGroup = [18, 21, 1, 1, 51, 18, 21, 5, 18, 7, 10];
let uniqueAgeGroup = ageGroup.reduce(function (accumulator, currentValue) < if (accumulator.indexOf(currentValue) === -1) < accumulator.push(currentValue); >return accumulator; >, []);console.log(uniqueAgeGroup); // [ 18, 21, 1, 51, 5, 7, 10 ]Example 4: Grouping Objects by a property
let people = [ < name: "John", age: 21 >, < name: "Oliver", age: 55 >, < name: "Michael", age: 55 >, < name: "Dwight", age: 19 >, < name: "Oscar", age: 21 >, < name: "Kevin", age: 55 >, ]; function groupBy(objectArray, property) < return objectArray.reduce(function (accumulator, currentObject) accumulatorJavascript reduce array to string.push(currentObject); return accumulator; >, <>); > let groupedPeople = groupBy(people, "age"); console.log(groupedPeople);
Reduce in javascript String array Code Example, The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in single output value. The reducer function takes four arguments: Accumulator (acc) Current Value (cur) Current Index (idx) Source Array (src) //syntax arr.reduce(callback( accumulator, currentValue, [, index[, …
JavaScript Array reduce()
Examples
Subtract all numbers in an array:
function myFunc(total, num) <
return total — num;
>Round all the numbers and display the sum:
const numbers = [15.5, 2.3, 1.1, 4.7];
document.getElementById(«demo»).innerHTML = numbers.reduce(getSum, 0);function getSum(total, num) <
return total + Math.round(num);
>Definition and Usage
The reduce() method executes a reducer function for array element.
The reduce() method returns a single value: the function’s accumulated result.
The reduce() method does not execute the function for empty array elements.
The reduce() method does not change the original array.