Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flatten an array of arrays in javascript for get the longest string

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; 
        });
}
like image 516
shakaran Avatar asked Mar 23 '23 04:03

shakaran


1 Answers

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;
}, '');
like image 71
plalx Avatar answered Apr 06 '23 00:04

plalx