ibeautiful
2022-10-13 19:27:03
試圖找出最好的方法來(lái)做到這一點(diǎn),而不會(huì)碰到壞的 bigO?;旧衔矣幸粋€(gè)值標(biāo)識(shí)符name,我只想object.id根據(jù) if獲取對(duì)象中的唯一值object.name === name,因此Set()將包含僅與找到名稱(chēng)的條件相關(guān)的 id。例子...const uniqueIds = new Set();const name = "billy";const objects = [ {id: 1, name: "billy"}, {id: 2, name: "billy"}, {id: 3, name: "jack"}, {id: 4, name: "kevin"},]用 [1,2] 實(shí)例化 uniqueIds 的最佳方法是什么?我真的必須使用 afilter()進(jìn)入一個(gè)新數(shù)組,然后使用map()to 然后使用uniqueIds.add(id)嗎?或者有沒(méi)有更好的方法使用類(lèi)似的快捷方式來(lái)做到這一點(diǎn)insert ids into uniqueIds where objects.name === name?
1 回答

繁星點(diǎn)點(diǎn)滴滴
TA貢獻(xiàn)1803條經(jīng)驗(yàn) 獲得超3個(gè)贊
您可以使用reduceandSet獲取唯一 ID
const name = "billy";
const objects = [
{id: 1, name: "billy"},
{id: 2, name: "billy"},
{id: 2, name: "billy"},
{id: 3, name: "jack"},
{id: 4, name: "kevin"},
]
const uniqueIds = objects.reduce((result, obj)=>{
if(obj.name === name) result.add(obj.id)
return result
}, new Set())
console.log(Array.from(new Set(uniqueIds)))
添加回答
舉報(bào)
0/150
提交
取消