简体   繁体   English

如何从数组中找到更长的字符串?

[英]How to find longer Strings from an Array?

I want to find Longer Strings from this array:我想从这个数组中找到更长的字符串:

const myArr = ["first", "second", "third", "fourth", "fifth", "sixth", "seven", "eighth"] const myArr = [“第一”、“第二”、“第三”、“第四”、“第五”、“第六”、“第七”、“第八”]

in this array "second","fourth","eighth" has length of 6. I want to return these in an array.在这个数组中“第二个”、“第四个”、“第八个”的长度为 6。我想在一个数组中返回这些。

const myArr = ["first", "second", "third", "fourth", "fifth", "sixth", "seven", "eighth"]

function longerStrings(arr) {
    let largeStrings = []
    let longerWord = ''
    for (let name of arr) {
        if (name.length > longerWord.length) {
            longerWord = name
            largeStrings.push(longerWord)
        }
    }
    return largeStrings
}
longerStrings(myArr)

expected output is : ["second","fourth","eighth"]预期输出是:[“第二”,“第四”,“第八”]

but returns =["first","second"]但返回 =["first","second"]

Easier if you use filter instead:如果您改用过滤器,则更容易:

const myArr = ["first", "second", "third", "fourth", "fifth", "sixth", "seven", "eighth"]
const longest = myArr.reduce((a, b) =>  a.length > b.length ? a : b);
const res = myArr.filter(el => el.length >= longest.length)
console.log(res)

That returns:返回:

["second","fourth","eighth"]

Or, as Sash mentions below, it can be done in a single pass, although the solution is not as readable:或者,正如 Sash 在下面提到的,它可以一次性完成,尽管解决方案不那么可读:

let max = 0;
const reducer = myArray.reduce((previous, current) => {
  if (current.length > max) {
    previous = [];
  }
  if (current.length >= max) {
    previous.push(current);
    max = current.length;
  }
  return previous;
}, []);

console.log(reducer);

When a word longer than any found so far is identified, you need to create an entirely new array (discarding any elements it had before in it), and put the new record-setting word in it.当识别出比迄今为止发现的任何单词更长的单词时,您需要创建一个全新的数组(丢弃之前在其中的任何元素),并将新的创纪录单词放入其中。 You also need to push a name to the array if the name being iterated over isn't record-setting, but is equal to the current record-setter.如果被迭代的名称不是记录设置,但等于当前记录设置器,您还需要将名称推送到数组。

 const myArr = ["first", "second", "third", "fourth", "fifth", "sixth", "seven", "eighth"] function longerStrings(arr) { let largeStrings = [] let longerWord = '' for (let name of arr) { if (name.length > longerWord.length) { longerWord = name largeStrings = [name]; } else if (name.length === longerWord.length) { largeStrings.push(name) } } return largeStrings } console.log(longerStrings(myArr));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM