是否有一种简短的方法可以找到字符串数组中最长的字符串?
像arr.Max(x => x.Length);
?
答案 0 :(得分:160)
var longest = arr.sort(function (a, b) { return b.length - a.length; })[0];
可能效率更高,但仅在Javascript 1.8/ECMAScript 5后可用,默认情况下在旧浏览器中不可用:
var longest = arr.reduce(function (a, b) { return a.length > b.length ? a : b; });
答案 1 :(得分:23)
我会做这样的事情
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];
}
}
alert(longest);
答案 2 :(得分:22)
对旧问题的新答案:在ES6中你可以做得更短:
Math.max(...(x.map(el => el.length)));
答案 3 :(得分:4)
var arr = [ 'fdgdfgdfg', 'gdfgf', 'gdfgdfhawsdgd', 'gdf', 'gdfhdfhjurvweadsd' ];
arr.sort(function (a, b) { return b.length - a.length })[0];
答案 4 :(得分:4)
使用Array.prototype - (排序类似于@katsPaugh和@deceze在我做小提琴时发布的内容)
var arr = [
"2 --",
"3 ---",
"4 ----",
"1 -",
"5 -----"
];
Array.prototype.longest=function() {
return this.sort(
function(a,b) {
if (a.length > b.length) return -1;
if (a.length < b.length) return 1;
return 0
}
)[0];
}
alert(arr.longest());
答案 5 :(得分:4)
我看到最短的解决方案
function findLong(s){
return Math.max.apply(null, s.split(' ').map(w => w.length));
}
答案 6 :(得分:3)
在ES6中,这可以通过reduce()
复杂度的O(n)
调用来完成,而不是使用sort()
的{{1}}解决方案:
O(nlogn)
答案 7 :(得分:3)
我提供了一种功能+递归方法。查看评论以了解其工作原理:
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)
答案 8 :(得分:1)
我会做这样的事情:
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");
答案 9 :(得分:1)
也许不是最快的,但肯定是可读的:
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"
数组函数map
。
答案 10 :(得分:1)
如果您的字符串已经拆分为数组,则不需要拆分部分。
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 :(得分:0)
来这里求解决方法,但看不懂,贴出我的版本;
const getLongestStr = (longestStr, str) => {
return longestStr.length > str.length ? longestStr : str;
}
var input = ['ali', 'Shahenshah', 'naqvi', 'hm'];
var longest = input.reduce(getLongestStr, "")
答案 12 :(得分:0)
function allLongestStrings(array) {
const newArr=[];
let temp = Math.max(...(array.map(el => el.length)));
array.forEach(item => {
if(temp == item.length){
newArr.push(item);
}
});
return newArr;
}
答案 13 :(得分:0)
这是我的简单解决方案
var arr = ["you", "are", "the", "love", "of", "my", "life"];
var sorted = arr.sort(function (a, b){
return b.length - a.length;
});
console.log(sorted[0])
答案 14 :(得分:0)
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
});
答案 15 :(得分:0)
在支持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))
答案 16 :(得分:0)
如果您期望超过一个,这将起作用:
_.maxBy(Object.entries(_.groupBy(x, y => y.length)), y => parseInt(y[0]))[1]
它使用lodash并返回一个数组。
答案 17 :(得分:0)
function findLongestWord(str) {
str = str.split(" ");
var sorted = str.sort(function(prev,current){
return prev.length - current.length;
});
var index = sorted.length;
str = sorted[index-1];
return str;
}
findLongestWord("The quick brown fox jumped over the lazy dog");
答案 18 :(得分:0)
var longest = (arr) => {
let sum = 0
arr.map((e) => {
sum = e.length > sum ? e.length : sum
})
return sum
}
它可以工作
答案 19 :(得分:0)
我对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);
答案 20 :(得分:-1)
var array = ["hello","falsey","undefined"];
var findLongestWord = function(array){
var longest = array.reduce(function(a,b){
return (a.length > b.length) ? a : b;
});
return longest;
}
findLongestWord(array);
答案 21 :(得分:-2)
这是我在5分钟前编写的非常简单的错误代码。我没有时间修复错误,但如果你明白了,你可以改变并使用它。
Array.prototype.MaxBy = function(fn) {
var max = 0;
var element;
for (var i = 0; i < this.length; i++) {
var ret = fn(this[i]);
if (ret > max) {
max = ret;
element = this[i];
}
}
return element;
};
function showOldestPerson() {
var array = [{ Name: "cihat", Age: 28 }, { Name: "Ali", Age: 30 }, { Name: "Kutlu", Age: 27}];
var person = array.MaxBy(function(item) {
return item.Age;
});
alert(person.Name);
}