返回数组中最长的字符串(JavaScript)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46125796/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 06:29:02  来源:igfitidea点击:

Return longest string in array (JavaScript)

javascriptarraysstringfor-loop

提问by leandraaar

So I'm trying to find the longest string in an array of strings. I've done a problem similar to this before where I had to return the length of the longest string. The thing is, my code works and returns 11 when it looks like this:

所以我试图在字符串数组中找到最长的字符串。我之前做过一个类似的问题,我必须返回最长字符串的长度。问题是,我的代码可以正常工作并在如下所示时返回 11:

var long1= 0;

var plorp = ["bbllkw", "oox", "ejjuyyy", "plmiis", "xxxzgpsssa", "xxwwkktt", "znnnnfqknaz", "qqquuhii", "dvvvwz"];

function longestString(arr){
  for (i=0; i<arr.length; i++){
      if (arr[i].length > long1){
        long1= arr[i].length;
      }

  }
  return long1;
}

but, if I change long1= arr[i].length;to long1 = arr[i];it just returns arr[0]instead. Am I missing something here? The loop seems to be iterating correctly otherwise.

但是,如果我改变long1= arr[i].length;long1 = arr[i];它只是返回arr[0]来代替。我在这里错过了什么吗?否则,循环似乎正在正确迭代。

Edit: that is to say, it returns bbllkw.

编辑:也就是说,它返回bbllkw.

采纳答案by leandraaar

Simply you must change long declaration to :

只需将长声明更改为:

var long1= '';

and in the for loop condition it should be

在 for 循环条件中它应该是

arr[i].length > long1.length

回答by Dekel

You can use reduceinstead:

您可以reduce改用:

var plorp = ["bbllkw", "oox", "ejjuyyy", "plmiis", "xxxzgpsssa", "xxwwkktt", "znnnnfqknaz", "qqquuhii", "dvvvwz"];
var longest = plorp.reduce(function(a, b) { 
  return a.length > b.length ? a : b
}, '');
console.log(longest);

Or ES6 version:

或者 ES6 版本:

var plorp = ["bbllkw", "oox", "ejjuyyy", "plmiis", "xxxzgpsssa", "xxwwkktt", "znnnnfqknaz", "qqquuhii", "dvvvwz"];
var longest = plorp.reduce((a, b) => a.length > b.length ? a : b, '');
console.log(longest);

回答by turmuka

Updated after a user wanted more basic solution

在用户想要更基本的解决方案后更新

In here we find the longest length of an array item with reducefunction, and then filter the array with the elements which have that length with filterfunction. It returns us multipleelements if they have the same but longest length

在这里,我们使用reduce函数找到数组项的最长长度,然后使用函数过滤具有该长度的元素的数组filter。如果它们具有相同但最长的长度,它会返回多个元素

var plorp = ['sameLength', 'someoth', 'asfzc', 'sameLLngth'];
    ln = plorp.reduce((r,s) => r > s.length ? r : s.length, 0);


const result = plorp.filter(pl => pl.length == ln);

console.log(result);

Old Answer

旧答案

If there are more than onelongest string in the array, it will return an array of them. If there is only one longest, it will return the string, and not an array.

如果数组中有多个最长的字符串,它将返回它们的数组。如果只有一个最长的,它将返回字符串,而不是数组。

var plorp = ["bbllkw", "oox", "ejjuyyy", "plmiis", "xxxzgpsssa", "xxwwkktt", "znnnnfqknaz", "qqquuhii", "dvvvwz"];
var wholeArr = [];

function longestString(arr) {
    var tlength = 0;
    for(var i =0; i < plorp.length; i++){
      if(tlength < plorp[i].length){
        tlength = plorp[i].length;
      }
    }
    for(var j =0; j < plorp.length; j++){
      if(plorp[j].length == tlength){
         wholeArr.push(plorp[j]);
      }
    }
   if(wholeArr.length == 1){
     return wholeArr[0]
   }else{
      return wholeArr
  }
}


console.log(longestString(plorp));

回答by Bharti Ladumor

var arr = ["first", "second", "third", "fourth", "thousand"]

function getLongestString(arr) { let longestStringArr = arr.sort((a, b) => a.length - b.length).reverse(); return longestStringArr[0]; }

console.log(getLongestString(arr))

var arr = [“第一”、“第二”、“第三”、“第四”、“千”]

函数getLongestString(arr) { letlongestStringArr = arr.sort((a, b) => a.length - b.length).reverse(); 返回longestStringArr[0]; }

console.log(getLongestString(arr))

回答by Daolagajao

Just compare the length of the strings and then assign the string itself to long1.

只需比较字符串的长度,然后将字符串本身分配给 long1。

var plorp = ["bbllkw", "oox", "ejjuyyy", "plmiis", "xxxzgpsssa", "xxwwkktt", "znnnnfqknaz", "qqquuhii", "dvvvwz"];

function longestString(arr) {
  var long1 = arr[0];
  for (i = 0; i < arr.length; i++) {
    if (arr[i].length > long1.length) {
      long1 = arr[i];
    }
  }
  return long1;
}


console.log(longestString(plorp));

回答by Zamrony P. Juhara

The problem is when you set

问题是当你设置

long1=arr[i];

And you compare with length which is integer value.

并且您与整数值的长度进行比较。

At first iteration, you compare integer value of 0 with length of first string which of course make the comparison expression result true and you set

在第一次迭代时,您将 0 的整数值与第一个字符串的长度进行比较,这当然会使比较表达式结果为真并设置

 long1=arr[0];

For next iteration, long1no longer contain integer value but string so comparison between length and long1always return false.

对于下一次迭代,long1不再包含整数值而是字符串,因此长度之间的比较long1始终返回false。

That is why you always get first string as result.

这就是为什么你总是得到第一个字符串作为结果。

You need to initialize long1as empty string and use long1.lengthfor comparison as suggested by belhadj's answer.

您需要按照belhadj 的回答的建议初始化long1为空字符串并long1.length用于比较。

回答by slevy1

Another solution involves the array's sortmethod and a comparison function, but that can be a "heavy" solution as per MDN:

另一种解决方案涉及数组的排序方法和比较函数,但根据MDN,这可能是一个“繁重”的解决方案:

Depending on the compareFunction's nature, this may yield a high overhead. The more work a compareFunction does and the more elements there are to sort, the wiser it may be to consider using a map for sorting.

根据 compareFunction 的性质,这可能会产生很高的开销。compareFunction 做的工作越多,需要排序的元素越多,考虑使用映射进行排序可能越明智。

So, taking the preceding advice, here's one way to obtain the longest string using a map in conjunction with an array's sort method, as follows:

因此,根据前面的建议,这里是使用映射和数组的排序方法获得最长字符串的一种方法,如下所示:

var plorp = ["bbllkw", "oox", "ejjuyyy", "plmiis",
             "xxxzgpsssa", "xxwwkktt", "znnnnfqknaz",
             "qqquuhii", "dvvvwz"];

function getLongestStr() {
  var mapped = plorp.map((el, i) => ({ index: i, length: el }) );
  mapped.sort((a, b) => {

      if (a.length > b.length) {
        return -1;
      }
   
      if (a.length < b.length) {
        return 1;
      }
      return 0;
  });

// DESC order so longest string in 0th element
  return mapped.map((el) => plorp[el.index])[0];
}
console.log( getLongestStr() );

Interesting related discussion here.

有趣的相关讨论在这里