简体   繁体   English

如何使用javascript / jquery实现排序但随机的列表

[英]How to achieve a sorted but random list with javascript/jquery

I currently use this code to randomly sort my list of items and it works quite well: 我目前使用此代码对我的项目列表进行随机排序,并且效果很好:

$(document).ready(function () {
(function ($) {
    $.fn.randomize = function (childElem) {
        return this.each(function () {
            var $this = $(this);
            var elems = $this.children(childElem);
            elems.sort(function () {
                return (Math.round(Math.random()) - 0.5);
            });
            $this.remove(childElem);
            for (var i = 0; i < elems.length; i++)
            $this.append(elems[i]);
        });
    };
})(jQuery);

(function ($) {
    if (window.location.href.indexOf("st=") > -1) {

    } else {
        $('#itemBlock').randomize('.list_1');
    }
})(jQuery);

});

However, I am stumped when it comes to figuring out a way to modify this script to randomly return results in a certain order. 但是,当我想出一种方法来修改此脚本以按一定顺序随机返回结果时,我感到很沮丧。 For instance, the list I use this with returns all of a specific type of item from all of 5 stores. 例如,与之配合使用的列表返回了所有5家商店中所有特定类型商品的清单。 So if someone is looking for an apron it will show all of the aprons we have at each of our 5 stores. 因此,如果有人在寻找围裙,它将显示我们5家商店中每家的所有围裙。

The code above surely randomizes the list, but I don't know how to take into account the store location. 上面的代码肯定会随机列出该列表,但我不知道如何考虑商店位置。

So right now a search for aprons would initially return from stores A, B, C, D, and E a list like this: 因此,现在搜索围裙将首先从商店A,B,C,D和E返回如下列表:

BCDAEBCDDDCEABBACACABCDAA BCDAEBCDDDCEABBACACABCDAA

But what we want to achieve is a return like this: 但是我们想要实现的是这样的回报:

ABCDEABCDEABCDEABCDEABCDE ABCDEABCDEABCDEABCDEABCDE

Not necessarily in exactly that order but someway to modify the function so that a result from each store is loaded before more results are loaded. 不一定完全按照该顺序,而是以某种方式修改函数,以便在加载更多结果之前先加载每个存储区的结果。 So there wouldn't be 3 in a row from one store, or one store would be represented more than others. 因此,一家商店不会连续出现3家商店,否则一家商店的代表人数会更多。

Do I go about this by using the filter or sort function? 我可以通过使用过滤器或排序功能来解决此问题吗? Or would pure javascript handle this more efficiently? 还是纯JavaScript会更有效地处理此问题?

To achieve this, you would have to follow the following steps: 为此,您必须执行以下步骤:

  1. Randomly sort the items from each store individually 分别对每个商店中的商品进行随机排序
  2. Number the items in each randomised list 为每个随机列表中的项目编号
  3. OPTIONAL - if you want the stores in order, pad the number with zeros and append an identifier for the store ( [padded item number]|[store identifier] eg 00001|A ) 可选-如果要按顺序订购商店,请在数字前加上零,然后为商店添加标识符( [padded item number]|[store identifier]例如00001|A
  4. Combine all the lists into one 将所有列表合并为一个
  5. Sort this new list by the ordered number (or string) 按顺序编号(或字符串)对该新列表进行排序

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM