如何將相同屬性的數組對象合併並統計個數

NO IMAGE

類別: 一題多解
博客: blog.csdn.net/qtfying
掘金: juejin.im/user/577399…
QQ: 2811132560
郵箱: [email protected]

這兩天在瀏覽博客的時侯,發現這樣一個題,就嘗試著去解了一把,現在把解的幾個方法貼出來,供大家參考和學習

目標數組為:

  let data = [{
id: '1',
goodsName: 'test',
price: 22
},
{
id: '2',
goodsName: 'test',
price: 22
},
{
id: '2',
goodsName: 'test',
price: 22
},
{
id: '3',
goodsName: 'test',
price: 22
},
{
id: '3',
goodsName: 'test',
price: 22
},
{
id: '3',
goodsName: 'test',
price: 22
},
{
id: '3',
goodsName: 'test',
price: 22
},
{
id: '4',
goodsName: 'test',
price: 22
}
]

目標結果為:

  let data = [{
id: '1',
goodsName: 'test',
price: 22,
count:1
},
{
id: '2',
goodsName: 'test',
price: 22,
count:2
},
{
id: '3',
goodsName: 'test',
price: 22,
count:4
},
{
id: '4',
goodsName: 'test',
price: 22,
count:1
}
]

分析題意:就是對象中一樣的item合併為一項,並且計數,為item增加count的鍵值

  • 第一種解決辦法為最原始的,也是最原始的去重方式
  var interimArray = [];   // 用來存放去重後的id的
var resultArray = [];   // 最終的期望結果
var count = 1;
for (var i in data) {
if (interimArray.indexOf(data[i].id) > -1) {
console.log(`${data[i].id}已經存在,計數加1`, `count為${count}`);
for (var j in resultArray) {
if (resultArray[j].id === data[i].id) {
count++;
resultArray[j].count = count;
}
}
} else {
count = 1;
console.log(`${data[i].id}不存在,數組加入${data[i].id}`, `count重置為${count}`);
interimArray.push(data[i].id);
data[i].count = count;
resultArray.push(data[i]);
}
}
console.log(JSON.stringify(resultArray, null, 2));
  • 第二種解決辦法為將id當鍵值,判斷該鍵值是否存在,在去取value成數組
  let result = {};
for (let i = 0, len = data.length; i < len; i++) {
let dataArr = data[i];
if (result[dataArr.id]) {
result[dataArr.id].count ++;
} else {
result[dataArr.id] = { ...dataArr, count: 1 };
}
}
let resultArr = [];
for (const key in result) {
resultArr.push(result[key]);
}
console.log(JSON.stringify(Object.values(result), null, 2));
  • 第三種類似於第二種只不過是利用Object.entries將第二種對象轉為二維數組
  // reduce的4個參數 prev, cur, index, arr
var twoDimensionalArray = Object.entries(data.reduce((prev, cur) => {
if (!prev[cur.id]) {
prev[cur.id] = {
...cur,
count: 1
};
} else {
prev[cur.id].count += 1;
}
return prev;
}, {}));
var result = twoDimensionalArray.map(entry => entry[1]);
console.log(JSON.stringify(result, null, 2));
  • 第四種是用reduce方法對第一種方法進行精簡
  let result = data.reduce((obj, item) => {
let find = obj.find(i => i.id === item.id);
let _d = {
...item,
count: 1
};
find ? find.count++ : obj.push(_d);
return obj;
}, []);
console.log(JSON.stringify(result, null, 2));

麻雀雖小,五臟俱全,一個題目考察點有數組的去重,Set,reduce,Object.keys(),Object.values(),Object.entries,二維數組,循環的三種方法:map、for、reduce等等

相關文章

2019與我的自由啟蒙

從零搭建完整的React項目模板(Webpack+Reacthooks+Mobx+Antd)【演戲演全套】

格式化時間用了YYYYMMdd,元旦當天老闆喊我回去改Bug!

什麼是可迭代對象(Iterableobjects)?