简体   繁体   English

最长的单词-JS

[英]Getting Longest Word - JS

I am writing a function that returns the longest string in the given array. 我正在写一个函数,该函数返回给定数组中最长的字符串。 If the array is empty, it should return an empty string (""). 如果数组为空,则应返回一个空字符串(“”)。 If the array contains no strings; 如果数组不包含任何字符串; it should return an empty string. 它应该返回一个空字符串。

function longestWord(arr) {
 var filtered = arr.filter(function(el) { return typeof el == 'number' });
  if (filtered.length > 0) {
    return Math.min.apply(Math, filtered);
  } else {
    return 0;
  }
}

var output = longestWord([3, 'word', 5, 'up', 3, 1]);
console.log(output); // --> must be 'word'

Right now my codes doesnt pull the word instead it pulls out the number. 现在我的代码没有拉这个词,而是拉出了数字。 Any idea what am I missing? 知道我想念什么吗?

Let's walk through your code. 让我们遍历您的代码。

The first line of your longestWord function: longestWord函数的第一行:

var filtered = arr.filter(function(el) { return typeof el == 'number' });

will filter the input array based on typeof el === 'number' , which will return an array containing only the elements of the input array which are type of === number . 将基于typeof el === 'number'过滤输入数组,这将返回一个数组,该数组仅包含type of === number的输入数组元素。

Since the goal is to find the longest word, this should probably be changed to: 由于目标是找到最长的单词,因此应将其更改为:

var filtered = arr.filter(function(el) { return typeof el === 'string' });

which will return an array of the strings in the input array. 这将返回输入数组中的字符串数组。

Next, there's a check to see if the filtered array is empty. 接下来,检查过滤后的数组是否为空。 If the array is empty, you return 0 . 如果数组为空,则返回0 Your instructions say that if the array is empty, or if the array contains no strings, it should return an empty string. 您的指令说,如果数组为空,或者数组不包含任何字符串,则应返回一个空字符串。 So we should change this to: 因此,我们应该将其更改为:

return "";

If the array is not empty, or contains strings, Math.min.apply(Math, filtered) is returned. 如果数组不为空或包含字符串,则返回Math.min.apply(Math, filtered) This statement would return the minimum value of an array, so probably not what you want. 该语句将返回数组的最小值,因此可能不会返回您想要的最小值。 After all, the goal is to return the longest string. 毕竟,目标是返回最长的字符串。

To do this we can use a variety of methods, here's one: 为此,我们可以使用多种方法,这是一种:

filtered.reduce(function(a, b) { return a.length > b.length ? a : b })

This statement uses the reduce() method to step through the array and return the longest item. 该语句使用reduce()方法单步执行数组并返回最长的项目。

Putting it all together we get: 放在一起,我们得到:

 function longestWord(arr) { var filtered = arr.filter(function(el) { return typeof el === 'string' }); if (filtered.length > 0) { return filtered.reduce(function(a, b) { return a.length >= b.length ? a : b }); } else { return ""; } } console.log(longestWord([3, 'word', 5, 'up', 3, 'testing', 1])); console.log(longestWord([])); console.log(longestWord([1, 2, 3, 4, 5])) console.log(longestWord(['some', 'long', 'four', 'char', 'strs'])) 

I assume the filter meant to be for "string" 我认为该过滤器旨在用于“字符串”

Once you have the filtered array, you can simply use reduce to get the longest word 获得过滤后的数组后,您可以简单地使用reduce来获得最长的单词

 function longestWord(arr) { return Array.isArray(arr) ? arr .filter(el => typeof el == 'string' ) .reduce((a,b) => b.length > a.length ? b : a) : ''; } console.log(longestWord([3, 'word', 5, 'up', 3, 1, 'blah'])); 

Even shorter code 更短的代码

var longestWord = (arr) => Array.isArray(arr) ? arr.reduce((a,b) => (typeof b == 'string' && b.length > a.length) ? b : a, '') : '';
const longestWord = arr =>
  arr.reduce((result, str) =>
    typeof str == 'string' && result.length < str.length
      ? str 
      : result, '')

This isn't the most efficient code. 这不是最有效的代码。 For that, seek other answers, especially those that use reduce , however I do find it more readable and thus easier to maintain: 为此,寻求其他答案,尤其是那些使用reduce答案,但是我确实发现它更具可读性,因此更易于维护:

 function longestWord(arr) { var filtered = arr.filter(el => typeof el === 'string') .sort((a,b) => a.length > b.length ? -1 : 1 ); if (filtered.length) return filtered[0]; return null; } var output = longestWord([3, 'word', 5, 'up', 3, 1]); console.log(output); // --> must be 'word' 

But what to do when two strings are the same length? 但是,当两个字符串长度相同时该怎么办?

As all other answers are using filter() , reduce() and all that new and fancy methods, I'm gonna answer with the do-it-yourself method (ie the old fashion way). 由于所有其他答案都使用filter()reduce()以及所有新的奇特方法,因此我将用自己动手做方法(即旧的方式)进行回答。

function longestWord(arr) {
    if ( ! ( typeof arr === 'array' ) ) {
        console.log("That's not an array!");
        return '';
    }

    var longest = ''; // By default, the longest word is the empty string

    // Linear search
    for ( var i = 0, length = arr.length; i < length; i++ ) {
        var el = arr[i];
        if ( typeof el === 'string' && el.length > longest.length ) {
            // Words STRICTLY GREATER than the last found word.
            // This way, only the first word (if two lengths match) will be considered.
            longest = el;
        }
    }

    return longest;
}

I know, this is probably NOT what you want since you're already using filtered() , but it works. 我知道,这可能不是您想要的,因为您已经在使用filtered() ,但是它可以工作。

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

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