我想找到一個陣列的重復元素和 2 個重復元素的陣列。
array = [
["41",{asd:"1"}],
["41",{asd:"2"}],
["42",{asd:"1"}],
["42",{asd:"2"}]
]
我想要的結果
result=[
["41",{asd:"1"},{asd:"2"}],
["42",{asd:"1"},{asd:"2"}],
]
我必須使用核心 JavaScript。不允許使用框架。
uj5u.com熱心網友回復:
- 使用
Array#reduce, 迭代陣列,同時更新 aMap其中key是數字,value是它的物件串列 - 使用
Array#map,回傳一個陣列串列,其中每個數字及其物件在一個陣列中
const array = [ ["41", {asd:"1"}], ["41", {asd:"2"}], ["42", {asd:"1"}], ["42", {asd:"2"}] ];
const res = [...
array.reduce((map, [key, obj]) =>
map.set(key, [...(map.get(key) || []), obj])
, new Map)
.entries()
]
.map(([key, objArr]) => [key, ...objArr]);
console.log(res);
uj5u.com熱心網友回復:
reduce在陣列上。在每次迭代中從陣列中提取鍵和物件。如果累加器上不存在該鍵,則添加它并將其值設定為[key],然后將物件推入其中。然后使用Object.values來獲取您需要的輸出。
const arr = [
["41",{asd:"1"}],
["41",{asd:"2"}],
["42",{asd:"1"}],
["42",{asd:"2"}]
];
const out = arr.reduce((acc, c) => {
const [key, obj] = c;
acc[key] = acc[key] || [key];
acc[key].push(obj);
return acc;
}, {});
console.log(Object.values(out));
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/362036.html
標籤:javascript 数组 目的
上一篇:我在python中回圈很慢
下一篇:最小化數量
