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

類別: 一題多解
博客: blog.csdn.net/qtfying
掘金: juejin.im/user/577399…
QQ: 2811132560
郵箱: qtfying@gamil.comjavascript

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

目標數組爲:數組

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的鍵值ui

  • 第一種解決辦法爲最原始的,也是最原始的去重方式
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等等spa

相關文章
相關標籤/搜索