从数组中获取最长的字符串

从数组中获取最长的字符串

本文介绍了从数组中获取最长的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到一个字符串数组和n表示应该返回多长字符串。我的意思是这个

I am given an array of strings and n which indicates how many longest strings should be returned. What I mean is this

longStr(["a", "ab", "abc", "abcd", "abcde"], 2)-> 'abcde abcd'



所以,如果n是n,它应该只返回1个字符串,这是数组中最长的字符串,如果n是2,它应该返回最长的字符串和第二个字符串最长的字符串。



我尝试过:




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:

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?

推荐答案

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);





参考 []



演示: []



根据 Richard Deeming的评论更新解决方案





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

demo:- JSFiddle[^]

Updated solution based on comments from Richard Deeming

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(' '); 
       }


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
}


这篇关于从数组中获取最长的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 08:32