0

I have a custom comparator for sorting some strings which doesnt work as expected for sorting strings in descending order.

var list = document.getElementById('mylist');

var items = list.childNodes;
var itemsArr = [];
for (var i in items) {
  if (items[i].nodeType == 1) { // get rid of the whitespace text nodes
    itemsArr.push(items[i]);
  }
}
var sortOrder = "DESC";

itemsArr.sort(function(a, b) {
  switch (sortOrder) {
    case "ASC":
      var val = a.innerHTML.localeCompare(b.innerHTML);
      break;
    case "DESC":
      var val = a.innerHTML.localeCompare(b.innerHTML);
      if (val === 1)
        val = -1;
      if (val === -1)
        val = 1;
      break;

  }
  return val
});

/*itemsArr.sort(function(a, b) {
  return a.innerHTML == b.innerHTML
          ? 0
          : (a.innerHTML > b.innerHTML ? 1 : -1);
});*/

for (i = 0; i < itemsArr.length; ++i) {
  list.appendChild(itemsArr[i]);
}
<ul id="mylist">
  <li id="list-item3">Service</li>
  <li id="list-item4">Vendor</li>
  <li id="list-item2">Service_Type</li>
  <li id="list-item1">Call_Date</li>
  <li id="list-item3">Customer Sat Rating</li>
  <li id="list-item4">TTA</li>
  <li id="list-item2">Support_Rep</li>
  <li id="list-item1">Source_State</li>
  <li id="list-item3">Severity</li>
  <li id="list-item4">Customer_Type</li>
  <li id="list-item2">CALL ID</li>
  <li id="list-item1">Resolved_Ontime</li>
  <li id="list-item2">Product</li>
  <li id="list-item1">Minutes_On_Phone</li>
</ul>

For a different data I sorted earlier it worked fine for both ascending and descending. For the current html data it doesnt. Can someone please show where I am incorrect?

4
  • 1
    You should not have duplicate id's, they mess up the lookup table for the DOM. Commented Oct 5, 2015 at 21:57
  • 1
    To do descending sort with .localeCompare() you just need to use the unary - operator: val = -val; Commented Oct 5, 2015 at 21:59
  • In my working code, I do not have duplicate ID's. This html snippet is for stackoverflow. Still Ill edit it Commented Oct 5, 2015 at 21:59
  • @Pointy: Any small snippet you can point me to, that would be great. Commented Oct 5, 2015 at 22:01

1 Answer 1

2

You are setting it to DESC and then right back again:

case "DESC":
  var val = a.innerHTML.localeCompare(b.innerHTML);
  if (val === 1)
    val = -1;
  if (val === -1)
    val = 1;
  break;

Change it to:

case "DESC":
  var val = -1 * a.innerHTML.localeCompare(b.innerHTML);
  break;
Sign up to request clarification or add additional context in comments.

1 Comment

You don't need the * operator. Just apply the - unary operator to the return value: -a.innerHTML.localeCompare(b.innerHTML)

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.