對javascript是個新手。我正在嘗試轉換一個數字陣列
。[ 12, 14, 12,10,11, 10 ]
進入一個物件陣列,鍵是陣列中的數字,后面是數字出現的索引陣列,如
。{'12'/span>。[0, 2]], '10': [3,5], '11': 4 }
我看到幾個例子都是用reduce,但我不明白如何為一個給定的鍵創建專案陣列。
uj5u.com熱心網友回復:
。 。const arr = [12, 14, 12, 10, 11, 10】。]
const map = new Map()。
arr.forEach((n, i) => (map.has(n) ? map.get(n).push(i) : map.set(n, [i]) )。
const result = {};
for (let [k, v] of map) {
v.length === 1 ? (result[k] = v[0] ) : (result[k] = v) 。
}
console.log(result);
/* This is not a part of answer. 它只是為了給輸出填充高度。所以請忽略它 */
.as-console-wrapper { max-height: 100% ! important; top: 0; }
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
uj5u.com熱心網友回復:
你可以使用Array#reduce,用一個物件作為累積器。
回呼被賦予前一個累加器、當前陣列元素和它的索引。
。let arr = [ 12, 14,12,10,11,10 ] 。
let res = arr.reduce((acc, curr, i)=> /span>
((acc[curr]?=[]).push(i), acc), {})。
console.log(res);
. as-console-wrapper{max-height:100%! important}
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/321046.html
標籤:
上一篇:WPF實作Win10漢堡選單
