问题
I want to find all the words from the string which have the greatest length.
At the moment, the result is just the first with the greatest length: 'jumped1'
, whereas I want them all: ['jumped1', 'jumped2']
.
How can I adapt the following?
function test(str) {
var newStr = str.split(' ');
var nu = 0;
var word =null;
for(var i=0; i < newStr.length; i++){
if(newStr[i].length > nu){
nu = newStr[i].length; // length
word = newStr[i]; // word
}
}
return word;
}
console.log(test("The quick brown fox jumped1 over the lazy dog - jumped2"));
回答1:
Instead of assigning to a variable, word
, when you find longest word, push it to an array of longest words. You have to handle blanking the array though when a new longest word is found.
function test(str) {
var split_string = str.split(' ');
var longest_length = 0;
var words = [];
for(let string of split_string){
if(string.length > longest_length){
words = [string];
longest_length = string.length;
} else if (string.length == longest_length){
words.push(string);
}
}
return words;
}
console.log(test("The quick brown fox jumped1 over the lazy dog - jumped2"));
回答2:
You can use reduce to get the length of the longest word and then filter to get the list of words of that length:
function test(str) {
var words = str.split(' ');
var maxLen = words.reduce(function(num, word){
return Math.max(num, word.length);
}, 0);
return words.filter(function(word){
return word.length == maxLen
});
}
console.log(test("The quick brown fox jumped1 over the lazy dog - jumped2"));
回答3:
If I understand the question correctly, you can use filter
after finding the max length in order to return an Array of every word with length === max
function test (str) {
let words = str.split(' ')
let max = 0
words.forEach(word => {
if (word.length > max) max = word.length
})
return words.filter(word => word.length === max)
}
console.log(
test("The quick brown fox jumped1 over the lazy dog - jumped2")
)
回答4:
You could reduce the array by collecting longer words or with same length.
function test(string) {
return string
.split(' ')
.reduce((r, w) => {
if (!r || r[0].length < w.length) {
return [w];
}
if (r[0].length === w.length) {
r.push(w);
}
return r;
}, undefined);
}
console.log(test("The quick brown fox jumped1 over the lazy dog - jumped2"));
来源:https://stackoverflow.com/questions/52130686/find-all-the-words-in-a-string-which-have-the-greatest-length