2013-02-10 97 views
0

我可以想象這已被問了幾次,但我實際上無法找到解決方案的例子,我試圖找出具體問題。按值排序對象

所以我有一個對象,像這樣:

var collection = [{ id: 0 }, { id: 1 }, { id: 2 }]; 

我然後有一個數組,這是「訂單」,如下所示:

var order = [2, 0, 1]; 

我想使用的「順序'數組按照該特定順序對集合進行重新排序。我一直在嘗試使用.sort函數的很多解決方案,但我找不到適合的解決方案。任何人都可以啓發我嗎?可能很簡單,我希望。

+0

不知道你的需求是什麼,但在這樣一個簡單的情況下,你可以通過索引來訂購。 – elclanrs 2013-02-10 23:42:39

+0

要警惕使用多個未緩存的'indexOf'調用的解決方案,因爲它們將涉及多次掃過'order'。 – Dancrumb 2013-02-10 23:46:20

回答

5

可以使用sort()方法來完成使用indexOf

collection.sort(function(a, b){ 
    return order.indexOf(a.id) > order.indexOf(b.id); 
}); 
+0

工作得很好,謝謝! – 2013-02-15 23:27:23

1

似乎是這麼簡單:

var collection = [{ id: 0 }, { id: 1 }, { id: 2 }]; 
var order = [2, 0, 1]; 
var sorted = []; 
for(var i=0,c=order.length;i<c;i++){ 
    sorted.push(collection[order[i]]); 
} 
+1

我不認爲這是OP所要求的。這需要'collection'並使用'order'來表示「列出第三個,然後是第一個,然後是第二個來自集合」。我認爲,OP要「列表ID:2,然後ID:0,然後ID:1」 – Dancrumb 2013-02-10 23:39:30

1

試一下:

var collection = [{ id: 0 }, { id: 1 }, { id: 2 }]; 
var order = [2, 0, 1]; 
var sortedCollection = []; 
for (var i = 0; i < order.length; i++) 
    sortedCollection.push(collection[order[i]]); 
console.log(sortedCollection); 
2

你可以使用indexOf函數在定製數組中的定單數組中T功能,像這樣:

collection.sort(function(x, y) { 
        return order.indexOf(x.id) > order.indexOf(y.id); 
       }); 
+0

似乎我需要輸入得更快,@ozk比我更快:(。 – Styxxy 2013-02-10 23:44:39

+1

StackOverflow是關於輸入敏捷:) – ozk 2013-02-10 23:47:13

0

要避免在這裏通過這兩種陣列掃描比你更需要的東西。

這裏有一個解決方案,避免了這一點:

/* 
* Map the indexes of the objects in collection to their final location 
*/ 
var sortIndex = {}; 
order.forEach(function(value, index) { 
    sortIndex[value] = index; 
}); 

/* 
* Put the objects in collection into their new, sorted collection 
*/ 
var sortedCollection = []; 
collection.forEach(function(value) { 
    var sortedLocation = sortIndex[value.id]; 
    sortedCollection[sortedLocation] = value; 

}); 

因此,我們必須通過每一個陣列的單次掃描,保持工作降低到最低限度。

我在這裏用forEach作爲方便;你可以使用像Lodash或Underscore這樣的庫,或者重寫這個來對數組使用顯式迭代。