[英]Finding longest string in array
Is there a short way to find the longest string in a string array?有没有一种简单的方法可以找到字符串数组中最长的字符串?
Something like arr.Max(x => x.Length);
像
arr.Max(x => x.Length);
? ?
Available since Javascript 1.8/ECMAScript 5 and available in most older browsers :从Javascript 1.8/ECMAScript 5 开始可用,并且在大多数旧浏览器中可用:
var longest = arr.reduce(
function (a, b) {
return a.length > b.length ? a : b;
}
);
Otherwise, a safe alternative:否则,一个安全的选择:
var longest = arr.sort(
function (a, b) {
return b.length - a.length;
}
)[0];
一个老问题的新答案:在 ES6 中,你可以做得更短:
Math.max(...(x.map(el => el.length)));
I would do something like this我会做这样的事情
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]; } } console.log(longest);
Maybe not the fastest, but certainly pretty readable:也许不是最快的,但肯定非常可读:
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"
The array function forEach has been supported since IE9+ . 从 IE9+ 开始支持数组函数forEach 。
In ES6 this could be accomplished with a reduce()
call in O(n)
complexity as opposed to solutions using sort()
which is O(nlogn)
:在 ES6 中,这可以通过
O(n)
复杂度的reduce()
调用来完成,而不是使用sort()
解决方案,即O(nlogn)
:
const getLongestText = (arr) => arr.reduce( (savedText, text) => (text.length > savedText.length ? text : savedText), '', ); console.log(getLongestText(['word', 'even-longer-word', 'long-word']))
var arr = [ 'fdgdfgdfg', 'gdfgf', 'gdfgdfhawsdgd', 'gdf', 'gdfhdfhjurvweadsd' ];
arr.sort(function (a, b) { return b.length - a.length })[0];
I provide a functional+recursive approach.我提供了一个函数+递归的方法。 See comments to understand how it works:
查看评论以了解它是如何工作的:
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)
Using Array.prototype - (sort is similar to what was posted by @katsPaugh and @deceze while I was doing a fiddle)使用 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());
I was inspired of Jason's function and made a little improvements to it and got as a result rather fast finder:我受到 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);
Speed results: http://jsperf.com/longest-string-in-array/7速度结果: http : //jsperf.com/longest-string-in-array/7
I would do something like this:我会做这样的事情:
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");
I see the shortest solution我看到最短的解决方案
function findLong(s){
return Math.max.apply(null, s.split(' ').map(w => w.length));
}
If your string is already split into an array, you'll not need the split part.如果您的字符串已经拆分为一个数组,则不需要拆分部分。
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");
In case you expect more than one maximum this will work:如果您期望超过一个最大值,这将起作用:
_.maxBy(Object.entries(_.groupBy(x, y => y.length)), y => parseInt(y[0]))[1]
It uses lodash and returns an array.它使用 lodash 并返回一个数组。
With ES6 and it support a duplicate string使用 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))
function max( input ) {
return input.reduce((a, b) => a.length <= b.length ? b : a)
}
var longest = (arr) => {
let sum = 0
arr.map((e) => {
sum = e.length > sum ? e.length : sum
})
return sum
}
it can be work它可以工作
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");
This is my simple solution这是我的简单解决方案
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])
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;
}
Came here for the solution, but could not understand much, posting my version;来这里寻求解决方案,但不太明白,发布我的版本;
const getLongestStr = (longestStr, str) => {
return longestStr.length > str.length ? longestStr : str;
}
var input = ['ali', 'Shahenshah', 'naqvi', 'hm'];
var longest = input.reduce(getLongestStr, "")
If you want to know the INDEX of the longest item:如果您想知道最长项目的 INDEX:
var longest = arr.reduce(
(a, b, i) => arr[a].length < b.length ? i : a,
0
);
(which can be a one-liner for those that love that stuff.... but it's split up here for readabilty) (对于那些喜欢这些东西的人来说,这可能是一个单行......但为了便于阅读,它在这里分开了)
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);
Modern browsers support a for...of
loop. 现代浏览器支持
for...of
循环。 The fastest and shortest way to solve this problem in Chrome, Safari, Edge, and Firefox is also the clearest:在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
; 在 IE 中,您可以使用
Array.forEach
; that's still faster and clearer than sorting or reducing the array.这仍然比排序或减少数组更快更清晰。
var largest = '';
arr.forEach(function(item) {
if (item.length > largest.length) largest = item
});
This is really simple buggy code I have written 5 minutes ago. 这是我在5分钟前编写的非常简单的错误代码。 I havent time to fix bugs but if you get the idea you can change and use it.
我没有时间修复错误,但如果你明白了,你可以改变并使用它。
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.