【问题标题】:Finding longest string in array查找数组中最长的字符串
【发布时间】:2011-06-29 13:16:31
【问题描述】:

有没有捷径可以在字符串数组中找到最长的字符串?

类似arr.Max(x => x.Length);?

【问题讨论】:

    标签: javascript


    【解决方案1】:

    Javascript 1.8/ECMAScript 5 起可用,大多数older browsers 可用:

    var longest = arr.reduce(
        function (a, b) {
            return a.length > b.length ? a : b;
        }
    );
    

    否则,一个安全的选择:

    var longest = arr.sort(
        function (a, b) {
            return b.length - a.length;
        }
    )[0];
    

    【讨论】:

    • 如果有 2 个或多个相同大小的字符串,结果应该是一个数组怎么办? reduce 在这种情况下不起作用,您必须迭代第一个结果。
    • @GismoRanas 这是一个不同的问题,您仍然可以将reduce 与返回数组的回调函数一起使用。
    【解决方案2】:

    一个老问题的新答案:在 ES6 中你可以做得更短:

    Math.max(...(x.map(el => el.length)));
    

    【讨论】:

    • 返回最长字符串的长度,而不是最长的字符串。
    • 要注意的另一件事是,这将遍历集合两次 O(n^2),而大多数其他选项只会遍历集合一次 O(n)。自定义比较器可能使用 sort 甚至可能是 O(log(n))
    • @CTS_AE 这两个遍历是独立的,所以我认为这是O(n) + O(n) = O(n),而不是O(n^2)
    • @JoshuaBreeden 是的,我相信你是正确的 ?
    【解决方案3】:

    我会做这样的事情

    var arr = [
      'first item',
      'second item is longer than the third one',
      'third longish item'
    ];
    
    var lgth = 0;
    var longest;
    
    for (var i = 0; i < arr.length; i++) {
      if (arr[i].length > lgth) {
        var lgth = arr[i].length;
        longest = arr[i];
      }
    }
    
    console.log(longest);

    【讨论】:

    • 这是最好的,因为它不会影响您的阵列。然而,如果您排序(如所选答案中所示),您的数组会被排序,而有时您不希望这样做。 +1,谢谢
    • 想知道为什么要在 for 循环中重新声明 var lgth?在不重新声明lgth 的情况下这样做会给我正确的答案。但是,我在自己的版本中将所有var 更改为let
    【解决方案4】:

    也许不是最快的,但肯定非常易读:

    function findLongestWord(array) {
      var longestWord = "";
    
      array.forEach(function(word) {
        if(word.length > longestWord.length) {
          longestWord = word;
        }
      });
    
      return longestWord;
    }
    
    var word = findLongestWord(["The","quick","brown", "fox", "jumped", "over", "the", "lazy", "dog"]);
    console.log(word); // result is "jumped"
    

    数组函数forEach has been supported since IE9+

    【讨论】:

      【解决方案5】:
      var arr = [ 'fdgdfgdfg', 'gdfgf', 'gdfgdfhawsdgd', 'gdf', 'gdfhdfhjurvweadsd' ];
      arr.sort(function (a, b) { return b.length - a.length })[0];
      

      【讨论】:

        【解决方案6】:

        在 ES6 中,这可以通过 reduce() 复杂度的 reduce() 调用来完成,而不是使用 sort() 的解决方案,即 O(nlogn)

        const getLongestText = (arr) => arr.reduce(
          (savedText, text) => (text.length > savedText.length ? text : savedText),
          '',
        );
        
        console.log(getLongestText(['word', 'even-longer-word', 'long-word']))

        【讨论】:

        • 我希望更多的人向下滚动到这里,因为这应该是公认的答案。如果由于某种原因你需要 ES5 语法并且不能使用胖箭头功能(悲伤的脸),你可以这样做:arr.reduce(function(savedText, text) { return text.length &gt; savedText.length ? text : savedText; }, '');
        • @maxshuty 无需滚动,这提供了与 9 年前发布的公认答案相同的解决方案。
        • @miken32 最初接受的答案是使用排序,这是次优的,但最近它被编辑了,我看到了
        • 不,它是在原始答案发布 10 分钟后在编辑中添加的。
        • @miken32 怎么会这样?原始答案于 2011 年发布,并于 2020 年编辑
        【解决方案7】:

        我提供了一种函数式+递归的方法。查看 cmets 了解其工作原理:

        const input1 = ['a', 'aa', 'aaa']
        const input2 = ['asdf', 'qwer', 'zxcv']
        const input3 = ['asdfasdf fdasdf a sd f', ' asdfsdf', 'asdfasdfds', 'asdfsdf', 'asdfsdaf']
        const input4 = ['ddd', 'dddddddd', 'dddd', 'ddddd', 'ddd', 'dd', 'd', 'd', 'dddddddddddd']
        
        // Outputs which words has the greater length
        // greatestWord :: String -> String -> String
        const greatestWord = x => y => 
              x.length > y.length ? x : y
              
        // Recursively outputs the first longest word in a series
        // longestRec :: String -> [String] -> String
        const longestRec = longestWord => ([ nextWord, ...words ]) =>
              //                                ^^^^^^^^^^^^
              // Destructuring lets us get the next word, and remaining ones!
              nextWord // <-- If next word is undefined, then it won't recurse.
                ? longestRec (greatestWord (nextWord) (longestWord)) (words) 
                : longestWord
        
        
        // Outputs the first longest word in a series
        // longest :: [String] -> String
        const longest = longestRec ('')
        
        const output1 = longest (input1)
        const output2 = longest (input2) 
        const output3 = longest (input3)
        const output4 = longest (input4)
        
        console.log ('output1: ', output1)
        console.log ('output2: ', output2)
        console.log ('output3: ', output3)
        console.log ('output4: ', output4)

        【讨论】:

        • 知道为什么这对我不起作用吗? const longRec = longWord => ([nextWord, ...words]) => ^ TypeError: undefined is not a function
        • @duke 我会看一下,但我猜是问题背后的原因。
        • @duke BTW,你能给我意见吗?您是否按原样使用代码?
        • 见下文。但它似乎甚至没有编译。但你是对的:只使用你的代码就可以了.... let obj = { "HostName": { "Generated": "@logon", "Value": "openPI", "LastRun": "2018-11- 15 07:57:50,186”},“HostIp”:{“生成”:“@cron”,“值”:“192.168.178.70”,“LastRun”:“2018-11-15 02:49:23,961”} , "Release": { "Generated": "@cron", "Value": "Raspbian GNU/Linux 9 (stretch)", "LastRun": "2018-11-15 02:49:24,099" } };
        • 很抱歉打扰你,我以为它没有编译。我没有数组。
        【解决方案8】:

        我受到 Jason 的功能的启发,对其进行了一些改进,结果发现速度相当快:

        function timo_longest(a) {
          var c = 0, d = 0, l = 0, i = a.length;
          if (i) while (i--) {
            d = a[i].length;
            if (d > c) {
              l = i; c = d;
            }
          }
          return a[l];
        }
        arr=["First", "Second", "Third"];
        var longest = timo_longest(arr);
        

        速度结果:http://jsperf.com/longest-string-in-array/7

        【讨论】:

          【解决方案9】:

          我看到了最短的解决方案

          function findLong(s){
            return Math.max.apply(null, s.split(' ').map(w => w.length));
          }
          

          【讨论】:

          • 我更喜欢那个,虽然它可能不是最快的
          • 这给出了长度而不是单词
          【解决方案10】:

          如果您的字符串已经拆分为数组,则不需要拆分部分。

          function findLongestWord(str) {
            str = str.split(' ');
            var longest = 0;
          
            for(var i = 0; i < str.length; i++) {
               if(str[i].length >= longest) {
                 longest = str[i].length;
                  } 
               }
            return longest;
          }
          findLongestWord("The quick brown fox jumped over the lazy dog");
          

          【讨论】:

            【解决方案11】:

            如果您期望超过一个最大值,这将起作用:

            _.maxBy(Object.entries(_.groupBy(x, y => y.length)), y => parseInt(y[0]))[1]
            

            它使用 lodash 并返回一个数组。

            【讨论】:

              【解决方案12】:

              ES6 支持重复字符串

              var allLongestStrings = arrayOfStrings => {
                let maxLng = Math.max(...arrayOfStrings.map( elem => elem.length))
                return arrayOfStrings.filter(elem => elem.length === maxLng)
              }
              
              let arrayOfStrings = ["aba", "aa", "ad", "vcd","aba"]
               
              console.log(allLongestStrings(arrayOfStrings))
              

              【讨论】:

                【解决方案13】:

                我会这样做:

                function findLongestWord(str) {
                   var array = str.split(" ");
                   var maxLength=array[0].length;
                   for(var i=0; i < array.length; i++ ) {
                      if(array[i].length > maxLength) maxLength = array[i].length
                   }
                 return maxLength;
                }
                
                findLongestWord("What if we try a super-long word such as otorhinolaryngology");
                

                【讨论】:

                  【解决方案14】:
                  function max( input ) {
                  return input.reduce((a, b) => a.length <= b.length ? b : a)
                  }
                  

                  【讨论】:

                    【解决方案15】:

                    如果你想知道最长项目的索引:

                    var longest = arr.reduce(
                            (a, b, i) => arr[a].length < b.length ? i : a,
                            0
                        );
                    

                    (对于那些喜欢这些东西的人来说,这可能是一个单行字……但为了便于阅读,它在这里被分开了)

                    【讨论】:

                      【解决方案16】:

                      Modern browsers support a for...of loop.在Chrome、Safari、Edge、Firefox中解决这个问题最快最短的方法也是最清楚的:

                      let largest = '';
                      for (let item of arr) {
                        if (item.length > largest.length) largest = item
                      }
                      

                      In IE, you can use Array.forEach;这仍然比排序或减少数组更快更清晰。

                      var largest = '';
                      arr.forEach(function(item) {
                        if (item.length > largest.length) largest = item
                      });
                      

                      【讨论】:

                        猜你喜欢
                        • 2014-06-26
                        • 1970-01-01
                        • 1970-01-01
                        • 1970-01-01
                        • 1970-01-01
                        • 1970-01-01
                        • 1970-01-01
                        • 2022-12-03
                        • 2020-09-27
                        相关资源
                        最近更新 更多