Reputation: 359
How would I find the total number of characters (including spacing and commas) in the array after using .reduce
?
Ex.
Say I had an array, that when using .reduce((prev, curr) => [prev, ', ', curr])
, would result in
array: item1, item2, item3
And when I find the amount of characters, it would be 19 (without 'array: ').
Upvotes: 0
Views: 76
Reputation: 6368
Do I understand the question correctly if that you want the sum of the lenghts of an array of strings?
// I would define the function sum as
const sum = (iterable, start = 0) => iterable.reduce((a, b) => a + b, start);
// then
let array = ['item1', 'item2', 'item3'];
// and we can sum their lengths like this
console.log(sum(array.map((s) => s.length)));
// but then we're off because you want a comma and a space between them all
// so we should start with 2 * (length of array - 1)
console.log(sum(array.map((s) => s.length), 2 * (array.length - 1)));
// iff we have a items at all ofcourse
array = [];
console.log(sum(array.map((s) => s.length),
array.length ? 2 * (array.length - 1) : 0));
But really, the join().length
solution others mentioned is cleverer.
Upvotes: 0
Reputation: 11613
Like this:
var sumCharLengths = ['alpha ',' beta ','gamma'].reduce((a, b) => a + b.length, 0);
a
is your "accumulator" valueb
is the current array item as the reducer "loops" over the array0
is the start value for your accumulatorMore documentation here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
Alternatively, without reduce()
, you could just join()
the array items and take the length of that result, e.g.:
var sumCharLengths = ['alpha ',' beta ','gamma'].join().length
Upvotes: 1
Reputation: 969
Here's one with .reduce()
const strLength = ["item1", "item2", "item3"].reduce((prev, curr) => `${prev}, ${curr}`).length
Upvotes: 1
Reputation: 628
I would suggest you do join
method instead of reduce
. For your case,
let array = ['item1', 'item2', ' item3 '];
const strLength = array.join().length;
Upvotes: 1