[英]Fastest way to sort object's array based on other's object's array property
I've got two objects arrays and both of them have columnId property. 我有两个对象数组,它们都具有columnId属性。 I want to make the order of the first object's array same as the order of the second.
我想使第一个对象的数组的顺序与第二个对象的顺序相同。
I've tried this: 我已经试过了:
filtered = visibleColumns.filter(function(v) {
return filtered.includes(v.colId);
});
where filtered
is my result array and visibleColumns
is array which order I need, but it doesn't work. 我的结果数组
filtered
在哪里,而visibleColumns
是我需要的顺序排列的数组,但这不起作用。
example of arrays: 数组的例子:
filtered = [{ colId:1, title: 'col1', size: 10 }, { colId:2, title: 'col2', size: 10 }]; visibleColumns = [{ colId:2, visible: true }, { colId:1, visible: true }];
You could create a Map
object which maps each colId
from visibleColumns
to it's index in the array. 您可以创建一个
Map
对象,将每个colId
从visibleColumns
映射到数组中的索引。 Get the index for each colId
while sorting filtered
获取每个目录
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)
You could create an object with the wanted order and take a default value for unknown id for sorting them to bottom. 您可以创建具有所需顺序的对象,并为未知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.