![](/img/trans.png)
[英]Sort JavaScript array of Objects based on the object's properties in custom way
[英]Fastest way to sort object's array based on other's object's array property
我有兩個對象數組,它們都具有columnId屬性。 我想使第一個對象的數組的順序與第二個對象的順序相同。
我已經試過了:
filtered = visibleColumns.filter(function(v) {
return filtered.includes(v.colId);
});
我的結果數組filtered
在哪里,而visibleColumns
是我需要的順序排列的數組,但這不起作用。
數組的例子:
filtered = [{ colId:1, title: 'col1', size: 10 }, { colId:2, title: 'col2', size: 10 }]; visibleColumns = [{ colId:2, visible: true }, { colId:1, visible: true }];
您可以創建一個Map
對象,將每個colId
從visibleColumns
映射到數組中的索引。 獲取每個目錄colId
排序時filtered
const filtered = [{ colId: 1, title: "col1", size: 10 }, { colId: 2, title: "col2", size: 10 }], visibleColumns = [{ colId: 2, visible: true }, { colId: 1, visible: true }]; const order = new Map(visibleColumns.map((o, i) => [o.colId, i])) filtered.sort((a, b) => order.get(a.colId) - order.get(b.colId)) console.log(filtered)
您可以創建具有所需順序的對象,並為未知ID取默認值以將其排序到最底端。
var filtered = [{ colId: 1, title: 'col1', size: 10 }, { colId: 2, title: 'col2', size: 10 }], visibleColumns = [{ colId: 2, visible: true }, { colId: 1, visible: true }], order = visibleColumns.reduce((o, { colId }, i) => (o[colId] = i + 1, o), {}); filtered.sort((a, b) => (order[a.colId] || Infinity) - (order[b.colId] || Infinity)); console.log(filtered);
.as-console-wrapper { max-height: 100% !important; top: 0; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.