Efficiently find an item in a Set [duplicate]

2019-09-01 03:51发布

This question already has an answer here:

if I need to find an object in a Set. The set does not contain a natural key to use as an index, so I can't use Map. There are several different types of predicates used to search the Set. It seems inefficient to do

const items = Array.from( mySet )
const found = items.find( item => someTest( item ) )

Unless there's black magic in the optimiser, it seems like it will enumerate twice. I know it exposes an iterator interface, but the Array.prototype.find interface is much more concise than using a for...of loop with a break statement.

Is there a better way?

3条回答
淡お忘
2楼-- · 2019-09-01 04:02

Use a Map instead with the id (unique identifier) as the key:

const items = [{ id: 1 }, { id: 2 }, { id: 3 }]
const itemsMap = new Map(items.map(o => [o.id, o]))

const item = itemsMap.get(1)

console.log(item)

查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-09-01 04:06

You have has method on Set to find existence of value.

let set = new Set([1,2,4,5,6,7])

console.log(set.has(2))
console.log(set.has(10))

查看更多
爷的心禁止访问
4楼-- · 2019-09-01 04:17

Sets implement the iterator interface, so you should be able to iterate them looking for your particular item. It will not be as nice and declarative as using a find with an hig order function, with will be much more efficient. You can of course encapsulate that logic to make it much nicer

const findInSet = (pred, set) => { 
    for (let item of set) if(pred(item)) return item;
}
const item = findInSet(someTest, mySet);
查看更多
登录 后发表回答