在 JavaScript 中对嵌套数组进行分组

javascriptweb developmentfront end technologyobject oriented programming更新于 2024/1/7 5:32:17

假设,我们有一个像这样的值数组 −

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

我们需要编写一个 JavaScript 函数来接收一个这样的数组。然后,我们的函数应该准备一个数组,其中的数据根据​​对象的"type"属性进行分组。

因此,对于上述数组,输出应如下所示−

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 ] }
]

相关文章


有用资源