0

I have an array of JavaScript objectss that have a string description. I am trying to implement a simplified sorting algorithm that will drop case, strip out HTML tags, and then strip out everything but letters and digits. I have:

DASHBOARD.todo_entries.sort(function(first, second)
  {
  var first_workbench = first.description.toLowerCase();
  var second_workbench = second.description.toLowerCase();
  first_workbench = first_workbench.replace(/<.*?>/, '');
  second_workbench = second_workbench.replace(/<.*?>/, '');
  first_workbench = first_workbench.replace(/[^_\w]/, '');
  second_workbench = second_workbench.replace(/[^_\w]/, '');
  console.log('"' + first_workbench + '", "' + second_workbench + '"');
  return (first_workbench > second_workbench);
  });

At present that is consistently generating a sort order with descriptions of:

Testing: d.
Testing: e.
Test: a.
Testing: f.
Test: c.
Test: b.
Testing: g.
Testing: b.
Testing: a.
Test: d.
Testing: c.
Testing: h.
Testing: i.
Testing: j.
Testing: k.
Testing: l.

What I'd expect to happen is that it would have "Test: [a-d]" appearing in order, and then "Testing: [a-l]" appearing in order.

I'm not sure how to code something that would naturally generate this order; it doesn't match their order of creation (I think the creation times/order of "Test: [a-d]" and "Testing: [a-l]" overlap, but they were individually created in sequential order).

I am getting similar, but not identical, results if I just set the function to compare the unaltered descriptions with either < or >. At least within "Test"/"Testing", an unaltered lexicographic search should coincide with the results of the search I want. I've searched a bit through my code and not found anything else obviously tampering with the ordering of that array.

Anything jump out as wrong?

Thanks,

4

1 回答 1

2

The JS Array.sort method takes a comparator function cmp(a, b) that should return 1 or another positive number (indicating a < b), -1 or another negative number (indicating b > a), or 0 (indicating equivalent values) - see the MDN docs. Yours returns a boolean, effectively only 1 or 0, so it won't sort correctly.

Try

return first_workbench === second_workbench ? 0 :
    first_workbench > second_workbench ? 1 : -1;

or similar.

于 2014-01-10T23:27:55.423 回答