15,919,132 members
See more:
I am given an array of strings and n which indicates how many longest strings should be returned. What I mean is this
JavaScript
`longStr(["a", "ab", "abc", "abcd", "abcde"], 2)-> 'abcde abcd'`

So, if n is n, it should return only 1 string, which is the longest on the array, if n is 2, it should return the longest string and the one which is the second longest.

What I have tried:

JavaScript
```function longest (n,v) {
var val = ""
for(var i = 0; i < n.length; i++){
var length = n[0].length;
if(n[i].length > length){val = n[i] + " " +n[i]; delete n[i]}
}
return val
}

console.log(longest( ["a", "ab", "abc", "abcd", "abcde"], 2));```

I was trying to find the longest string and then remove it and then iterate again and add it but was stuck. Is it better to use recursion here?
Posted
Updated 10-Aug-16 8:07am
Is this a question somewhere from Code Fights? They used to show such questions, with no sense at all.

## Solution 1

try this

JavaScript
```function longStr(array, max)
{
var result = '';
array.sort(function (a, b) { return b.length - a.length; }); // sort by length (descending)
max = max >= array.length ? array.length : max; // validate for the max count less than array length
for (var i = 0; i < max; i++) {
result += array[i] + ' ';
}
return result;
}

longStr(["a", "ab", "abc", "abcd", "abcde"], 2);```

refer Array.prototype.sort() - JavaScript | MDN[^]

demo:- JSFiddle[^]

Updated solution based on comments from Richard Deeming

JavaScript
```function longStr(array, max)
{
var result = '';
array.sort(function (a, b) { return b.length - a.length; }); // sort by length (descending)
max = max >= array.length ? array.length : max; // validate for the max count less than array length
return array.slice(0, max).join(' ');
}
```

v4
Richard Deeming 10-Aug-16 13:26pm
It might be simpler to use slice[^] to extract the first `n` elements of the array.

`return array.slice(0, max);`
Karthik_Mahalingam 10-Aug-16 13:42pm
yes Correct, but the Op needs the answer in this format `'abcde abcd'`
any ways he can customise it.

updated the solution.
Maciej Los 10-Aug-16 16:57pm
Good catch!
Maciej Los 10-Aug-16 16:57pm
5ed!
Karthik_Mahalingam 10-Aug-16 21:54pm
Thank you Maciej

## Solution 2

try:
JavaScript
```function longest (n,v) {
var val = n[0];
var length = n[0].length;
for(var i = 1; i < n.length; i++){
if(n[i].length > length){
val = n[i];
length = n[i].length;
}
}
return val
}```