I am trying to flatten an array of arrays in a input, and return the longest string.
For example given the input:
i = ['big',[0,1,2,3,4],'tiny']
The function should return 'tiny'. I would like use reduce or concat for resolve this in a native and elegant way (without implement a flatten prototype in array) but I am failing with this code:
function longestStr(i)
{
// It will be an array like (['big',[0,1,2,3,4],'tiny'])
// and the function should return the longest string in the array
// This should flatten an array of arrays
var r = i.reduce(function(a, b)
{
return a.concat(b);
});
// This should fetch the longest in the flattened array
return r.reduce(function (a, b)
{
return a.length > b.length ? a : b;
});
}
Your issue is that you forgot to pass in the initialValue
argument to the reduce function, which must be an array in this case.
var r = i.reduce(function(a, b) {
return a.concat(b);
}, []);
Without providing an initialValue
, the a
value for the first call will be the first element in the i
array, which is the string big in your case, so you will be calling the String.prototype.concat
function instead of Array.prototype.concat
.
That means at the end, r
is a string and strings don't have a reduce
function.
Your solution could be simplified however:
['big',[0,1,2,3],'tiny'].reduce(function longest(a, b) {
b = Array.isArray(b)? b.reduce(longest, '') : b;
return b.length > a.length? b : a;
}, '');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With