Sorting a list by data-attribute

后端 未结 3 1421
借酒劲吻你
借酒劲吻你 2020-12-20 02:16

I have a list of people with job titles sorted by the persons’ first names, like this:

3条回答
  •  失恋的感觉
    2020-12-20 02:48

    This works for any number of lists: it basically gathers all lis in uls that have your attribute, sorts them according to their data-* attribute value and re-appends them to their parent.

    Array.from(document.querySelectorAll("ul > li[data-azsort]"))
      .sort(({dataset: {azsort: a}}, {dataset: {azsort: b}}) => a.localeCompare(b)) // To reverse it, use `b.localeCompare(a)`.
      .forEach((item) => item.parentNode.appendChild(item));
    
    

    The funny thing is, it gets all lis in the same array, sorts them all, but in the end figures out which list the li originally belonged to. It’s a pretty simple and straight-forward solution.


    A slightly longer ECMAScript 5.1 alternative would be:

    Array.prototype.slice.call(document.querySelectorAll("ul > li[data-azsort]")).sort(function(a, b) {
      a = a.getAttribute("data-azsort");
      b = b.getAttribute("data-azsort");
    
      return a.localeCompare(b);
    }).forEach(function(node) {
      node.parentNode.appendChild(node);
    });
    

提交回复
热议问题