2016-01-23 34 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上的工作示例。