-4
var arr = [
"rohan",
"markandeya",
"hanumante",
"sapan",
"Ritesh"
];

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());

Need to understand the above code line by line. I exactly didn't get function(a,b) part can any one explain it.

Rohan H
  • 29
  • 4
  • 1
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort – j08691 Mar 21 '16 at 14:00
  • a,b just pop from anywhere. Can you check the code again? – anshabhi Mar 21 '16 at 14:00
  • 1
    You should probably start with something more basic – wvdz Mar 21 '16 at 14:04
  • 1
    Possible duplicate of [How does sort function work in JavaScript, along with compare function](http://stackoverflow.com/questions/6567941/how-does-sort-function-work-in-javascript-along-with-compare-function) – legoscia Mar 21 '16 at 14:05
  • Although you already accepted my answer, I just realized I missed a part of what the code did, that is very relevant. I've edited my answer to include this part, at the bottom. – Hans Roerdinkholder Mar 22 '16 at 09:08

1 Answers1

0
var arr = [
"rohan",
"markandeya",
"hanumante",
"sapan",
"Ritesh"
];

This defines an array of strings and assigns it to the variable arr

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

This creates a new function longest and adds it to the prototype of Array. In short, adding to the prototype makes the new function available to any object with type Array in your application. E.g., you can now call arr.longest() as seen in the last line of your code: (because arr is of type Array)

alert(arr.longest());

Now for the interesting part. Array.prototype already contains a sort function. This function expects a parameter that is a compare function. In other words, you have to define HOW items in the array are sorted by describing how two items are compared to see which one comes first in the sort process. This function is here defined as:

   function(a,b) {  
      if (a.length > b.length) return -1;
      if (a.length < b.length) return 1;
        return 0
    }

Now, Array.prototype.sort, as I said, expects a sort callback. This callback is expected to return either 0, 1 or -1 to indicate the order in which two items (here named a and b, but these names are arbitrary) should be sorted.

It seems from reading this function, that the items are sorted by a property length. Since your array arr is an array of strings, and strings have a length property, this works just fine.

So why 0, 1 or -1? From MDN: Array.prototype.sort(): (click link for more info)

If compareFunction is supplied, the array elements are sorted according to the return value of the compare function. If a and b are two elements being compared, then:

If compareFunction(a, b) is less than 0, sort a to a lower index than b, i.e. a comes first.

If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements. Note: the ECMAscript standard does not guarantee this behaviour, and thus not all browsers (e.g. Mozilla versions dating back to at least 2003) respect this.

If compareFunction(a, b) is greater than 0, sort b to a lower index than a.

compareFunction(a, b) must always return the same value when given a specific pair of elements a and b as its two arguments. If inconsistent results are returned then the sort order is undefined.

Edit

I missed some details about the code that are important to mention:

The function longest does not just sort the array. I read over this part when I first posted my answer. If we look at the following snippet:

return this.sort(
  function(a,b) {  
    if (a.length > b.length) return -1;
    if (a.length < b.length) return 1;
      return 0
  }
)[0];

Pay attention to the return and [0] parts. As I explained, this.sort will sort the array arr based on string length (longest first). Then, the first item of the result of the sort function is taken by [0]. The first item is the longest, because the array was sorted. This is then returned by the function longest. So in effect, the longest function returns the longest string in an array, by first sorting that array by length and returning the first item (with index 0) in that sorted array.

Hans Roerdinkholder
  • 3,000
  • 1
  • 20
  • 30
  • var arr = [ "1----", "2 ----", "3 --", "48883632634322178942", "4888-sharukh-khan", "sharukh ----" ]; var longest = ''; for (var i = 0; i < arr.length; i++) { if ( arr[i].length > longest.length ) { longest = arr[i]; } } alert(longest); We can do by this way also the easy way to find the longest string in an array. – Rohan H Mar 25 '16 at 17:14
  • Yes, there are multiple ways to solve this problem. Yours is very straight forward, but I think the GOOD thing about the code you originally posted is that it uses existing functions, instead of 're-inventing the wheel'. Do note that sorting the whole array, just to find the longest item, seems overkill and should NOT be done if performance is a concern. In that case, your solution posted in the comment is probably better. Also, do note that many consider it BAD practise to edit the prototype of existing types (like adding 'longest' to Array.prototype). – Hans Roerdinkholder Mar 26 '16 at 09:09