Sorting a list alphabetically with a modulus

后端 未结 4 1959
春和景丽
春和景丽 2021-02-08 20:07

I don\'t have any trouble grabbing a list of elements and sorting them alphabetically, but I\'m having difficulty understanding how to do it with a modulus.

###

4条回答
  •  一个人的身影
    2021-02-08 20:46

    var columnify = function (a,n) { 
        var result = []; 
        for (var i = 0, lastIndex = a.length - 1; i < lastIndex; i++) 
           result.push(a[i * n % (lastIndex)]); 
        result[lastIndex] = a[lastIndex];
        return result; 
    }
    
    var products = ["Boots",
    "Eyewear",
    "Gloves",
    "Heated Gear",
    "Helmet Accessories",
    "Helmets",
    "Jackets",
    "Mechanic's Wear",
    "Pants",
    "Protection",
    "Rainwear",
    "Random Apparel",
    "Riding Suits",
    "Riding Underwear",
    "Socks",
    "Vests",]
    
    columnify(products, 4)
    ["Boots", "Helmet Accessories", "Pants", "Riding Suits", "Eyewear", "Helmets", "Protection", "Riding Underwear", "Gloves", "Jackets", "Rainwear", "Socks", "Heated Gear", "Mechanic's Wear", "Random Apparel", "Vests"]
    

    Apply that function to the already sorted list, and then it will return a list of strings in the order (almost) that you want. Then add the list that was returned in order to the unordered list in the DOM.

    Also, I haven't tested it with anything besides that list. So I'd do that if I were you. From what I see, it only works if the length of the list is a multiple of n. Not that great of a solution but it's late for me and I can't be bothered to come up with anything better.

    EDIT: fixed the issue with the last element

提交回复
热议问题