对JS数组中的相同元素进行分组,但仅当连续时

2022-06-29 00:00:00 arrays grouping javascript

我有一个对象数组,表示聊天中的一系列"消息"。我想对由存储在每个数组项中的相同‘用户’连续创建的消息进行分组。以下是我正在尝试做的事情的简化版本:

[
    { message: "One", user: "Bob" },
    { message: "Two", user: "Bob" },
    { message: "Three", user: "Bob" },
    { message: "Hello", user: "Sam" },
    { message: "Hello", user: "Bob" },
    { message: "Hello", user: "Sam" },
    { message: "Hello", user: "Sam" }
]

应改为:

[
    [
        { message: "One", user: "Bob"},
        { message: "Two", user: "Bob" },
        { message: "Three", user: "Bob" }
    ],
    [
        { message: "Hello", user: "Sam" }
    ],
    [
        { message: "Hello", user: "Bob" }
    ],
    [
        { message: "Hello", user: "Sam" },
        { message: "Hello", user: "Sam" }
    ]
]

有什么简单的方法可以做到这一点吗?我在任何地方都找不到答案/算法。


解决方案

您可以使用reduce方法执行此操作。

数据-lang="js"数据-隐藏="假"数据-控制台="真"数据-巴贝尔="假">
const data = [
  { message: "One", user: "Bob" },
  { message: "Two", user: "Bob" },
  { message: "Three", user: "Bob" },
  { message: "Hello", user: "Sam" },
  { message: "Hello", user: "Bob" },
  { message: "Hello", user: "Sam" },
  { message: "Hello", user: "Sam" }
];

const result = data.reduce((acc, value) => {
  // compare the current value with the last item in the collected array
  if (acc.length && acc[acc.length - 1][0].user == value.user) {
    // append the current value to it if it is matching
    acc[acc.length - 1].push(value);
  } else {
    // append the new value at the end of the collected array
    acc.push([value]);
  }

  return acc;
}, []);
  
console.log(result);

相关文章