簡體   English   中英

如何按屬性值數組長度對對象進行排序?

[英]how to sort objects by property value array length?

我有兩個 arrays 如下所示:

const arr = [ 4, 5 ]
const arr2 = [
{
    "id": 1
    "type":[4]
},{
    "id": 2
    "type":[4,1]
},{
    "id": 3
    "type":[4,8,3]
},{
    "id": 4
    "type":[4,5]
}
]

如何以這種方式對arr2進行排序,即:

  1. 這樣如果arr2type包含arr中的所有元素,則這些對象位於列表的最頂部,

  2. 當它至少有一個帶有arr2的元素時,應該在下一個 position 中,

  3. 最后一個應該是在arr中僅列出一個( type中唯一的一個)的對象,

所以,結果應該是:

const arr2 = [
{
    "id": 4
    "type":[4,5]
},{
    "id": 2
    "type":[4,1]
},{
    "id": 3
    "type":[4,8,3]
},{
    "id": 1
    "type":[4]
}
]

我嘗試使用 js` function 來做到這一點,如下所示:

arr2.sort(e => e.type.includes(arr))

但它不能正常工作,可以告訴我如何以提供的方式對arr2進行排序嗎? 謝謝你的幫助!

您可以計算出現次數並按降序排序。

 const getCount = array => types.reduce((s, t) => s + array.includes(t), 0), types = [4, 5], data = [{ id: 6, type: [] }, { id: 1, type: [4] }, { id: 2, type: [4, 1] }, { id: 3, type: [4, 8, 3] }, { id: 4, type: [4, 5] }, { id: 5, type: [1, 2, 3] }]; data.sort(({ type: a}, { type: b }) => { const countA = getCount(a), countB = getCount(b); return countB - countA || (countA === 1 && a.length === 1) - (countB === 1 && b.length === 1); }); console.log(data);
 .as-console-wrapper { max-height: 100%;important: top; 0; }

您可以通過添加weight function 來優雅地做到這一點,這樣更重要的元素會得到更少的“權重”並從字面上上升到開頭:

 const KEYS = [4, 5] const arr2 = [ {"id": 1,"type": [4]}, {"id": 2,"type": [4, 1]}, {"id": 3,"type": [4, 8, 3]}, {"id": 4,"type": [4, 5]} ] function weight(a) { let common = a.reduce((cnt, x) => cnt + KEYS.includes(x), 0) if (common === KEYS.length) return 0 if (common > 0 && a.length > 1) return 1000 + a.length if (common > 0) return 10_000 return Infinity } arr2.sort(({type: x}, {type: y}) => weight(x) - weight(y)) console.log(arr2)

 const arr = [4, 5]; const arr2 = [ { id: 1, type: [4], }, { id: 2, type: [4, 1], }, { id: 3, type: [4, 8, 3], }, { id: 4, type: [4, 5], }, ]; console.log( arr2.sort((e) => -e.type.length).sort((e) => arr.every((aType) => e.type.includes(aType))? -1: e.type.includes(arr)? 0: 1, ), );

首先,我們按長度對數組進行排序以滿足條件(3),使 object 在末尾具有一種元素類型。

這個預排序的數組仍然需要根據(1)和(2)進行排序。

為了測試 (1) 我們查看every的返回值,如果它是true ,我們返回-1以將它放在結果數組的末尾。 如果它不是真的,我們需要測試(2)。

(2) 的剩余測試只需通過另一個調用來完成includes ,如果找到元素,我們返回0 ,這意味着它保留在預排序數組的 position 處。 如果沒有找到,我們通過返回1在數組末尾對其進行排序。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM