[英]reduce and map: how to get the same results
我正在使用reduce
並且我的代碼工作正常,但是,我正在嘗試使用map
,但不確定如何實現它。 任何幫助,將不勝感激。
該程序有什么作用?
下面我從 API 獲取許多 ID 的數據(這些是角色 ID),然后獲取與人類特征相關的特征(一個特征可以有很多特征)並過濾掉
null
特征,因為我不想要這些特征,然后對特征進行排序按字母順序排列。 最后 api 數據的數據結構應該保持不變。
使用reduce
:(實現讓我得到正確的輸出)
const characteristicsReduce = ids.reduce((acc, id) => (
{
...acc,
[id]: data?.codes[id]?.traits.filter((trait) => trait !== null).sort((traitOne, traitTwo) => {
if (traitOne.name < traitTwo.name) return -1;
if (traitOne.name > traitTwo.name) return 1;
return 0;
}),
}
), {});
我的 output 應該匹配:
{123: Array(20), 456: Array(20)}
問題 1:如何使用map
function 編寫相同的代碼?
問題 2:如果map
function 成功,在這種情況下應該首選哪個, map
還是reduce
,為什么?
雖然您在技術上可以像這樣使用map
:
const characteristicsReduce = {};
ids.map((id) => {
characteristicsReduce[id] = data?.codes[id]?.traits.filter((trait) => trait !== null).sort((traitOne, traitTwo) => {
if (traitOne.name < traitTwo.name) return -1;
if (traitOne.name > traitTwo.name) return 1;
return 0;
});
});
您也可以使用forEach
或常規的 for 循環。 不要像這樣濫用 MAP。
reduce
是通往 go 的方法,因為您正試圖將一組 ID 縮減為一個 object。
我更喜歡這個:更好的復雜性(避免在 reduce 的每次迭代中傳播累加器)並且如果記住 object 條目是[ [keyA, valueA], [keyB, valueB], ...]
const traitsForID = id => data?.codes[id]?.traits.filter(t => t).sort((a, b) => a.name.localeCompare(b.name));
const entries = ids.map(id => ([id, traitsForID(id)]);
const characteristicsViaMap = Object.fromEntries(entries)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.