当前位置: 首页 > 知识库问答 >
问题:

javascript - 数组分组问题?

汤飞翮
2023-08-04

我有一个数组,数组格式如下:

  [    {      id: 1,      name: 1,      msg: {        masterId: 1,        stackId: 2      }    },    {      id: 2,      name: 2,      msg: {        masterId: 1,        stackId: 2      }    },    {      id: 3,      name: 3,      msg: {        masterId: 3,        stackId: 3      }    },    {      id: 4,      name: 4    }  ]

想要根据msg中的masterId和stackId进行分组,masterId标识数据属于父元素,如果masterId和id相同,说明该元素为父元素,stackId标识这个设备属于一个组,最后想得到的格式如下

[  {      id: 1,      name: 1,      msg: {        masterId: 1,        stackId: 2      },      children: [      {          id: 2,          name: 2,          msg: {            masterId: 1,            stackId: 2          }        }      ]    },    {      id: 3,      name: 3,      msg: {        masterId: 3,        stackId: 3      }    },    {      id: 4,      name: 4    }]

请问该怎么做?

共有2个答案

壤驷坚
2023-08-04

时间复杂度 O(n),示例如下:

function func(array) {  const result = new Map();  for (const { id, name, msg } of array) {    if (msg && msg.masterId === id) {      result.set(id, { id, name, msg, children: [] });    } else if (msg && result.has(msg.masterId)) {      result.get(msg.masterId).children.push({ id, name, msg });    } else {      result.set(id, { id, name, msg });    }  }  return Array.from(result.values());}
长孙谦
2023-08-04
let arr = [  {    id: 1,    name: 1,    msg: {      masterId: 1,      stackId: 2    }  },  {    id: 2,    name: 2,    msg: {      masterId: 1,      stackId: 2    }  },  {    id: 3,    name: 3,    msg: {      masterId: 3,      stackId: 3    }  },  {    id: 4,    name: 4  }];let result = arr.reduce((acc, cur) => {   let parent = acc.find(item => item.id === cur.msg?.masterId);  if (parent) {    if (!parent.children) {      parent.children = [];    }    parent.children.push(cur);  } else {    acc.push(cur);  }  return acc;}, []);console.log(result);
 类似资料:
  • ui是这样的 后台返回的数据如下: 由于是gaugingTableList是数组包含多个对象。 需求是要取到数组中下面的数组的要取箭头的值 请问大佬们 , 像这种 要如何实现跟ui给的原型图一样的效果 由于arr放回来的数据比较多。这边就写了这样的代码 es6语法 识别不了,只能用原生,因为是工具控制的

  • 实现数组去重并对重复的元素进行标记,如果重复 "isRepeat": true",否则为 "isRepeat": false" 但是函数实际输出的元素都标记为 "isRepeat": true"

  • 我有下面的形式的数组 我想根据id和name对其进行分组,得到下面形式的数组,代码要如何编写?

  • a=[78,187,30] b=[78,186,185,25,30] c=[78,187,186,185,25,30] //想获得的结果 a=[1,2,3,4,5] b=[1,6,7,8,3,9,5] c=[1,2,6,7,8,3,4,9,5] //想获得的结果 a、b数组里面的值都是唯一的,怎么用js获得想要的值呢? 问了ChatGPT都没解决,它给的方法在控制台输出结果不一致,因为chatGP

  • 我有一个这样的数组: 。我想将数组按不同的组进行排序,如下所示: 因此,正如您所看到的,排序方法应该将所有数组分组,它们的值匹配在一起(如升序行) 因此,以上示例中的值-- 组-- 顺便说一句:my_array-数组已经排序,因此

  • 存在一个二维数组 const a = [{mac: 11, children: [{mac: 2}]}, {mac: 12, children: [{mac: 3}]}] 如何快速统计出mac的所有取值并返回一个数组[11, 2, 12, 3]?,顺序没有要求,不使用解构语法