我有一個字符串數組,可以將其視為模板/參考:
// Template
let template = ['A', 'B', 'C'];
我還有一個包含一些數組字符串的對像數組:
// Source (to be sorted)
let source = [
{ items: ['B', 'D', 'E'] },
{ items: ['E', 'L', 'Y'] },
{ items: ['G', 'B', 'A'] },
{ items: ['C', 'B', 'A'] }
];
我現在需要找到一種通過匹配數組(從最好到最壞)來對數組items
中的進行排序的方法。中字符串的順序無關緊要。source
template
items
根據我上面的示例,排序後的結果如下所示:
// Result after sorting
let sorted = [
{ items: ['C', 'B', 'A'] }, // 3 matches (A, B, C)
{ items: ['G', 'B', 'A'] }, // 2 matches (A, B)
{ items: ['B', 'D', 'E'] }, // 1 match (B)
{ items: ['E', 'L', 'Y'] } // no match
];
使用 JavaScript 方法 .sort() 和 .localCompare() 我可以根據字符串對數組進行排序,但我找不到按給定數組“模板”排序的方法。
如果有人知道如何做到這一點,我會非常高興?先感謝您!
您可以將邏輯基於Set
包含來自template
和 的不同元素的的大小items
。越小Set
,越常見的項目:
const template = ['A', 'B', 'C'];
const source = [
{ items: ['B', 'D', 'E'] },
{ items: ['E', 'L', 'Y'] },
{ items: ['G', 'B', 'A'] },
{ items: ['C', 'B', 'A'] }
];
const target = source
.map(({items}) => ({items, size: new Set([...items, ...template]).size}))
.sort((a, b) => a.size - b.size);
console.log(target);
如果您沒有處理數組中的不同值,這可能更合適:
const template = ['A', 'B', 'C'];
const source = [
{ items: ['B', 'D', 'E'] },
{ items: ['E', 'L', 'Y'] },
{ items: ['G', 'B', 'A'] },
{ items: ['C', 'B', 'A'] }
];
const target = source
.map(({items}) => ({
items,
size: items.reduce((a, v) => a + template.includes(v), 0)
}))
.sort((a, b) => b.size - a.size);
console.log(target);
這可以再次通過將 轉換template
為 a來進一步優化Set
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句