Smooth an array of arrays in javascript to get the longest string

I am trying to flatten an array of arrays in the input and return the longest string.

For example, given input:

i = ['big',[0,1,2,3,4],'tiny'] 

The function should return "tiny". I would like to use reduce or concat to resolve this in a native and elegant way (without implementation, smooth the prototype in an array ), but I cannot 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; 
        });
}
+4
source share
2 answers

Your problem is that you forgot to pass the argument initialValueto the reduce function , which in this case should be an array.

var r = i.reduce(function(a, b) {
    return a.concat(b);
}, []);

initialValue a i, , String.prototype.concat Array.prototype.concat.

, r - , reduce.

:

['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;
}, '');
+6

, - IE8...

function longestStr(A){
    var i= 0, len, A= String(A).split(/\b/).sort(function(a, b){
        return a.length<b.length;
    });
    len= A[0].length;
    while(A[i].length==len)++i;
    return A.slice(0, i);
}

var A1= ['big', [0, 1, 2, 3, 4], 'tiny',[1,2,3,'puny']];
longestStr(A1);

/*  returned value: (Array)
tiny,puny
*/

2:

-

, .

-

:

function longestStr(array){
    function flatten(arr){
        var A1= [], L= arr.length, next;
        for(var i= 0; i<L; i++){
            next= arr[i];
            if(next.constructor!= Array) A1.push(String(next));
            else A1= A1.concat(flatten(next));
        }
        return A1;
    }
    var i= 0, len, A=flatten(array);
    A.sort(function(a, b){
        return a.length<b.length;
    });
    len= A[0].length;
    while(A[i].length== len)++i;
    return A.slice(0, i);
}
var Ax= ['big stuff', [0, 1, 2, 3, 4], 'tiny', [1, 2, 3, 'puny']];
longestStr(Ax);

/*  returned value: (Array)
big stuff
*/
0

All Articles