按特定顺序显示对象并重复

时间:2016-01-23 02:11:02

标签: javascript arrays

我有以下数组

[ { 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

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

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

例如,上面的数组将导致项目按以下顺序显示:

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

我需要尽可能高效地完成这项工作。

1 个答案:

答案 0 :(得分:0)

为什么不循环浏览对象并搜索每种类型?

// 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上的工作示例。