javascript - 用不同标签的对象中的数组汇总数组

标签 javascript arrays dictionary filter reduce

我有一个包含对象的数组,其中一些具有相同的“子数组”但标签不同。我需要基于平等来总结那些。

到目前为止,比较两个不同的数组很容易,但我不确定如何在同一个数组中进行比较。 这是我的阵列。

let array = [{
  label: 'sting1',
  subArray: ['A', 'B']
}, {
  label: 'sting2',
  subArray: ['B']
}, {
  label: 'sting3',
  subArray: ['A', 'B']
}]

如您所见,标有String1String3 的对象具有相同的数组。所以现在我需要总结一下。我需要的结果是这样的:

let result = [{
  label: ['sting1', 'string3'],
  subArray: ['A', 'B']
}, {
  label: ['sting2'],
  subArray: ['B']
}]

最佳答案

这个问题很可能是一个通用的“分组依据”,尽管它涉及一些问题,主要是:

  • 您需要按一组项目进行分组。因为您没有指定受威胁的数组是通过引用还是通过值相同,我们需要假设您可能需要单独比较每个值。
  • 关于上面所说的,我假设您的数组由仅基元组成。
  • 标签似乎是按出现顺序排序的,所以我假设您希望按照它们在原始数组中出现的相同顺序收集它们。

也就是说,您可以使用 Array.reduce 遍历原始数组,并逐步:

  • 检查累加器是否已经有所需的键(不幸的是,在您的场景中,它不能通过简单的查找来完成。从技术上讲,您可以使用 Wea​​kMap,但这会稍微复杂一些)。在您的情况下,关键是您的子数组。因此,如果累加器中有任何项具有当前循环的子数组,您只需将标签插入现有项即可。
  • 如果没有,您只需推送当前循环的项目,假设您不关心引用。如果您不想更改原始 array 值,请首先对其进行深度复制
  • 一切都完成后,只需返回累加器并继续直到完成。

下面是一个示例代码构建用于您发布的场景:

let array = [{
  label: 'sting1',
  subArray: ['A', 'B']
}, {
  label: 'sting2',
  subArray: ['B']
}, {
  label: 'sting3',
  subArray: ['A', 'B']
}];

const grouped = array.reduce((acc, next) => {
  const { subArray } = next; // <-- acquire the subArray of the currently looped item.
  const exists = acc.find(({subArray: registeredSubArray}) => registeredSubArray.every(i => subArray.indexOf(i) > -1));
  // ^-- checks whether, in the accumulator, said subarray exists and if every item of the subarray is matched through indexOf against the accumulator looped item.
  if (exists) exists.label.push(next.label); // <-- if the item already exists, simply collect the label.
  else acc.push(Object.assign(next, {label: [next.label]})); // <-- otherwise, create a new object and assign the label as an array of labels instead of a single label.
  return acc; // finally, return the accumulator and continue.
}, []);

console.log(grouped);

关于javascript - 用不同标签的对象中的数组汇总数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57792521/

相关文章:

javascript - Cordova 多页面应用程序是否可以改善垃圾收集?

javascript - 按下 JQM 列表中的按钮

arrays - 二分搜索性能比线性搜索差

arrays - 任意数量数组的交集

python - 将字典理解应用于 defaultdict

python - 如何使用循环将变量添加到字典中?

javascript - 解码来自 Ajax 调用的 Json 响应

javascript - Jquery 最大宽度语句

c - 不使用方括号旋转矩阵 "[ ]"

list - python 中 if 的单行代码——为什么结果总是列表中的最后一项?