首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在javascript中合并、合并或展平多维数组

如何在javascript中合并、合并或展平多维数组
EN

Stack Overflow用户
提问于 2018-07-15 05:02:18
回答 2查看 65关注 0票数 -2

我有一个数组,那就是有相应预订的会议室。会议室是重复的,但相应的预订将是不同的,我不希望重复的会议室,并合并每个会议室的所有预订。

代码语言:javascript
复制
This is what I have:
['conference room one', ['reservation 2', 'reservation 1', 'reservation 3']]
['conference room two', ['reservation 7', 'reservation 5', 'reservation 6']]
['conference room two', ['reservation 10', 'reservation 11', 'reservation 12']]
['conference room one', ['reservation 9', 'reservation 8', 'reservation 15']]
['conference room one', ['reservation 17', 'reservation 14', 'reservation 13']]


This is what I want:
['conference room one', ['reservation 2', 'reservation 1', 'reservation 3', 'reservation 9', 'reservation 8', 'reservation 15', 'reservation 17', 'reservation 14', 'reservation 13']]
['conference room two', ['reservation 7', 'reservation 5', 'reservation 6', 'reservation 10', 'reservation 11', 'reservation 12']]

(删除了这里的一张截图,因为它无关紧要,让人分心)

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-07-15 05:11:40

您可以使用Array.reduce()创建映射并对所有值进行分组,之后只需使用Object.values()获取所有值的数组。

尝试以下操作:

代码语言:javascript
复制
var arr = [['conference room one', ['reservation 2', 'reservation 1', 'reservation 3']],
['conference room two', ['reservation 7', 'reservation 5', 'reservation 6']],
['conference room two', ['reservation 10', 'reservation 11', 'reservation 12']],
['conference room one', ['reservation 9', 'reservation 8', 'reservation 15']],
['conference room one', ['reservation 17', 'reservation 14', 'reservation 13']]];

var result = Object.values(arr.reduce((a,curr)=>{
  if(!a[curr[0]]){ // if the room is not present in map than add it.
    a[curr[0]] = curr;
  } else{ // if room exist than simply concat the reservations array of map and current element
      a[curr[0]][1] = a[curr[0]][1].concat(curr[1]);
  }
  return a;
},{}));

console.log(result);

票数 0
EN

Stack Overflow用户

发布于 2018-07-15 05:08:16

另一种方法是使用函数reduce对会议及其预订进行分组,并使用函数Object.values提取分组的值。

代码语言:javascript
复制
let array = [['conference room one', ['reservation 2', 'reservation 1', 'reservation 3']],['conference room two', ['reservation 7', 'reservation 5', 'reservation 6']],['conference room two', ['reservation 10', 'reservation 11', 'reservation 12']],['conference room one', ['reservation 9', 'reservation 8', 'reservation 15']],['conference room one', ['reservation 17', 'reservation 14', 'reservation 13']]],
    result = Object.values(array.reduce((a, [conference, reservations]) => {
      (a[conference] || (a[conference] = [conference, []]))[1].push(...reservations);
      return a;
    }, {}));

console.log(result);
代码语言:javascript
复制
.as-console-wrapper { max-height: 100% !important; top: 0; }

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51343354

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档