方案1:(reduce + find)
首先使用reduce函数将所有的选项扁平化到一个数组中,然后通过find函数查找具有特定ID的项并返回其值。这种方法在数据量适中的情况下工作良好,但是当数据量变得非常大时,性能会受到影响,因为find需要遍历整个数组直到找到匹配的元素或者遍历完所有元素。
时间复杂度为 O(n)。
方案2:(Map)
虽然构建Map的过程中确实涉及到了遍历操作,这是O(n)的时间复杂度(其中n是optionsGroup中所有options的数量)。
但是对于非常大的数据集,Map的查找通常会更快,因为哈希表的平均查找时间复杂度接近O(1),而数组的线性查找是O(n)。
总结:
如果有多次查找需求或数据量极大,使用Map更高效;如果是一次性查找或数据量不大,方案1的性能也完全可以接受。
// 需求: 已知optionsGroup中的所有options中的id肯定是唯一的
// 并且肯定有且仅有一个能匹配上selectId,找到对应的value。
let selectId = "1_1"
let optionsGroup = [
{
id: "0",
label: "",
options: [
{
id: "0_0",
value: "xxx"
},
{
id: "0_1",
value: "yyy"
}
]
},
{
id: "1",
label: "",
options: [
{
id: "1_0",
value: "aaa"
},
{
id: "1_1",
value: "bbb"
}
]
}
]
// 方案1:(reduce + find)
const allOptions = optionsGroup.reduce((acc, currentItem) => {
return acc.concat(currentItem.options)
}, [])
let targetValue1 = allOptions.find((e) => e.id == selectId).value
console.log(targetValue1)
// 方案2:(Map)
const idToValueMap = new Map()
optionsGroup.forEach((group) => {
group.options.forEach((option) => {
idToValueMap.set(option.id, option.value)
})
})
let targetValue2 = idToValueMap.get(selectId)
console.log(targetValue2)