2016-01-23 62 views
-4

我有以下阵列以特定的顺序显示对象,并重复

[ { 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,类型测试2

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

类型3,类型1,类型2,然后类型3,类型1,类型2和重复。所以基本上,类型2总是在类型1之后,而类型3总是在类型2之后或者在开始之后。要被显示在下面的顺序

例如,阵列上方将导致物品:

ID 5,ID 1,ID 3,ID 6,ID 2,ID 4

我需要做的这尽可能高效。

+4

你先试一下然后再回来看看我们! – James111

+0

在最后一个对象中,您的JSON中存在拼写错误:它缺少逗号。 –

回答

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