The Problem

The function is supposed to so something simple. There are a number of dynamic data structures that look something like this:

  var itemArray = [
      {"@id": "abc7",  other: "props", found: "here"},
      {"@id": "abc42", other: "props", found: "here"},
      {"@id": "abc19", other: "props", found: "here"},
      {"@id": "abc36", other: "props", found: "here"},
  ];

The actual objects are of course more complex. There are arrays containing different types of objects. One type will have a leading "abc" in the id prefix. Another will have "xyz", or some other string. Although they are often in order, they could be randomly arranged. What we want it a function that picks off the numeric portion of the ids, and returns the largest one.

For the array above, the function should return 42.

The Original Solution

This is the code found in production:

  01 function getCurrentId(itemArray) {
  02     var nextId = 0;
  03     var ids = [];
  04     var id = "";
  05
  06     $(itemArray).each(function (idx) {
  07         id = this["@id"];
  08         var regexp = /\d.*/g;
  09         regexp.compile(regexp);
  10         ids[idx] = this["@id"].substring(
  11             regexp.exec(id).index,this["@id"].length
  12         );
  13     });
  14  
  15    if (ids.length > 0) {
  16        nextId = ids.sort(function(a,b){return a-b;}).reverse()[0];
  17    }
  18  
  19    return nextId;
  20 }

There are numerous flaws in this code. What ones can you see?