14

If I have the following array :

array = ['a', 'abcde', 'ab'] ;

I would like to get the maximum length of the array elements ie 5 (for the element 'abcde').

I know that you can get the length of an array element via (eg) array[1].length but I don't know how to get the maximum length.

Any answer in JavaScript or jQuery would be great.

TIA

Paul Jones

1
  • Thanks for all the replies. All the solutions worked perfectly with the example I gave, where all the array elements are strings. For anyone who is interested, a slight addition has to be made (I think) if the array elements are numeric : $.each(myarray, function(i, item) { item = String(item) // addition maxLength = Math.max(maxLength, item.length); alert(item + ' ' + maxLength) }); If there is a 'smarter' way of doing this, let me know. Thanks again for the help Paul Jones Commented May 19, 2011 at 19:55

8 Answers 8

25

One-liner for you:

 Math.max.apply(Math, $.map(array, function (el) { return el.length }));

Working example: http://jsfiddle.net/5SDBx/

You can do it without jQuery in newer browsers (or even older browsers with a compatibility implementation of Array.prototype.map) too:

Math.max.apply(Math, array.map(function (el) { return el.length }));
Sign up to request clarification or add additional context in comments.

4 Comments

Heh, I was just about to write exactly that line, although possibly without jQuery.
@Tim Without jQuery? Are you mad? :P
@Tim: yeah, thought about it but IE8 and lower made me think again :-) edit: added.
You already had your +1. What do I do now? Have a "well done". Well done.
15

A new answer to an old question: in ES6 you can do even shorter:

Math.max(...array.map(el => el.length));

Comments

6

In such cases, there is a very useful function. Array.reduce

['a', 'abcde', 'ab'].reduce((r,s) => r.length > s.length ? r : s, 0);

This will return the longest string. To get its length, use:

['a', 'abcde', 'ab'].reduce((m,x) => x.length > m ? x.length : m, 0);

Comments

5

One (possibly rubbish) way of doing that, without using Jquery:

var myarray = ['a','abcde','ab'];
var maxlen = 0;
for (i=0; i<myarray.length; i++) {
  if (myarray[i].length>maxlen) {
    maxlen = myarray[i].length;
  }
}

3 Comments

Nothing wrong with a good old for loop, likely it's faster than other solutions. You might test for a native each method first though.
Judging by the downvote received, I guess self-deprecation isn't a good idea on here. Good idea about the each though.
It is possible to convert this to self contained expression using Array.reduce.
3

By using Array.prototype.reduce(), you can elegantly perform a Math.max() calculation for each item in the array. It does not matter whether the items in the array are string or sub-arrays (2D array, matrix, etc.), this will work because String and Array both have a prototype.length() function.

I also added a check for integer values per your comment above.

function arrayItemMax(arr) {
    return arr.reduce(function (result, val) {
        return Math.max(result, !isNaN(val) ? parseInt(val) : val.length);
    }, 0);
}

function print(text) {
  document.getElementsByTagName('body')[0].innerHTML += text + '<br />';
}

print(arrayItemMax(['a', 'abcde', 'ab'])); // 5
print(arrayItemMax([1, 5, 2]));            // 5
print(arrayItemMax(['1', '5', '2']));      // 5

One liner:

function(a){return a.reduce(function(r,v){return Math.max(r,!isNaN(v)?parseInt(v):v.length);},0);}

Comments

2

You could use jQuery's each() to iterate a little nicer.

var maxLength = 0;

$.each(array, function(i, item) {
   maxLength = Math.max(maxLength, item.length);
});

Or plain ol' JavaScript...

var maxLength = 0;

for (var i = 0, length = array.length; i < length; i++) {
   maxLength = Math.max(maxLength, array[i].length);
};

1 Comment

Thanks for all the replies - all the solutions worked perfectly. For anyone who is interested, a slight addition has to be made if the array elements are numeric :
0

There are several ways to do that.

I would iterate through all the array elements and store the longest element in a local variable. You get the longest element by comparing the first array element with the second, then storing the longer one. Then go on and compare each element with the longest one so far.

You just need one loop to do that.

Comments

0

You can create own your code. Follow this ->

Array.prototype.count = function(){  return this.length; }

then use

arr = [ "erhan",1,"sonmez",2 ];
arrCount = arr.count();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.