【问题标题】:Displaying objects in a certain order and repeat按一定顺序显示对象并重复
【发布时间】:2016-01-23 02:11:01
【问题描述】:

我有以下数组

[ { id: 1, type: "test1" }, { id: 2, type: "test1" }, { id: 3, type: "test2" }, { id:4, type: "test2" }, { id: 5, type: "test3" }, { id: 6 type: "test3" } ]

我需要按以下顺序显示项目(使用 javascript)

先输入 3,再输入 1,再输入 2,然后再重复输入 test3,输入 test1,输入 test 2

我得到一个对象数组,每个对象都有一个类型属性。如何有效地对数组进行排序,以便始终获得以下顺序:

键入 3,键入 1,键入 2,然后键入 3,键入 1,键入 2,然后重复。所以本质上,类型 2 总是在类型 1 之后,类型 3 总是在类型 2 之后或开头。

例如上面的数组会导致item按如下顺序显示:

id 5,id 1,id 3,id 6,id 2,id 4

我需要尽可能高效地做到这一点。

【问题讨论】:

  • 你先尝试一下,然后再回来找我们怎么样!
  • 您在最后一个对象中的 JSON 中有错字:它缺少一个逗号。

标签: javascript arrays


【解决方案1】:

为什么不直接遍历对象并搜索每种类型?

// order of types to loop through
var order = ["test3", "test1", "test2"];

// your data set
var objects = [ { id: 1, type: "test1" }, { id: 2, type: "test1" }, { id: 3, type: "test2" }, { id:4, type: "test2" }, { id: 5, type: "test3" }, { id: 6, type: "test3" } ];

// array to put sorted values into
var sortedArray = [];

// loop through as many times as the number of objects
// i = loop iteration counter, j = index of words
for(var i = 0, j = 0; i < objects.length; i++, j++) {

    // j cycles through the possible types
    if(j == order.length)
        j = 0;

    // find the word that matches the current type
    for(var k = 0; k < objects.length; k++) {

        // if word has not been matched already and has the correct type ...
        if(order[j] == objects[k].type && sortedArray.indexOf(objects[k].id) < 0) {

            // add it to the output array and exit
            sortedArray.push(objects[k].id);
            break;
        }
    }
}

// sorted result stored in `sortedArray` variable

请参阅JSFiddle.net 上的工作示例。

【讨论】:

    猜你喜欢
    • 2019-12-16
    • 2014-09-24
    • 1970-01-01
    • 2023-02-01
    • 2021-11-20
    • 2021-04-23
    • 2018-10-11
    • 2018-01-12
    • 2014-06-18
    相关资源
    最近更新 更多