按 JavaScript 中的巢狀陣列進行分組


假設我們有如下一個值陣列 −

const arr = [
   {
      value1:[1,2],
      value2:[{type:'A'}, {type:'B'}]
   },
   {
      value1:[3,5],
      value2:[{type:'B'}, {type:'B'}]
   }
];

我們需要編寫一個 JavaScript 函式,該函式採用一個這樣的陣列。然後,我們的函式應準備一個數組,其中資料根據物件的“型別”屬性進行分組。

因此,對於上面的陣列,輸出應如下所示 −

const output = [
   {type:'A', value: [1,2]},
   {type:'B', value: [3,5]}
];

例子

其程式碼將為 −

const arr = [
   {
      value1:[1,2],
      value2:[{type:'A'}, {type:'B'}]
   },
   {
      value1:[3,5],
      value2:[{type:'B'}, {type:'B'}]
   }
];
const groupValues = (arr = []) => {
   const res = [];
   arr.forEach((el, ind) => {
      const thisObj = this;
      el.value2.forEach(element => {
         if (!thisObj[element.type]) {
            thisObj[element.type] = {
               type: element.type,
               value: []
            }
            res.push(thisObj[element.type]);
         };
         if (!thisObj[ind + '|' + element.type]) {
            thisObj[element.type].value =
            thisObj[element.type].value.concat(el.value1);
            thisObj[ind + '|' + element.type] = true;
         };
      });
   }, {})
   return res;
};
console.log(groupValues(arr));

輸出

並且控制檯中的輸出將為 −

[
   { type: 'A', value: [ 1, 2 ] },
   { type: 'B', value: [ 1, 2, 3, 5 ] }
]

更新於:23-11-2020

705 次瀏覽

開啟你的 職業生涯

完成課程獲得認證

開始
廣告