I've got two objects arrays and both of them have columnId property. 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.
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. Get the index for each colId
while sorting 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.
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; }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.