Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
192 views
in Technique[技术] by (71.8m points)

javascript - 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);?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Available since Javascript 1.8/ECMAScript 5 and available in most older browsers:

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];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...