将相同元素组合到JS数组中,但仅当连续时

时间:2018-11-18 17:35:52

标签: javascript arrays grouping

我有一个对象数组,代表聊天中的一系列“消息”。我想对由相同“用户”连续创建的消息进行分组,该消息存储在每个数组项中。这是我要做的事情的简化版本:

[
    { 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" }
    ]
]

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

4 个答案:

答案 0 :(得分:1)

您可以使用reduce方法。

enable.auto.commit = true
auto.commit.interval.ms = 5000
auto.offset.reset = smallest
log.retention.hours=168

答案 1 :(得分:0)

您可以执行以下操作:

const messages = [
    { 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" }
]

let currentUser;
let groupedMessages = [];

for (message of messages) {

  if (message.user !== currentUser) {
    groupedMessages.push([]);
    currentUser = message.user;
  }
  groupedMessages[groupedMessages.length - 1].push(message)
}

console.log(groupedMessages);

答案 2 :(得分:0)

您可以检查最后一个元素,如果它没有相同的用户,则创建一个新数组。

var 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" }],
    grouped = data.reduce((r, o, i, a) => {
        if (!i || a[i - 1].user !== o.user) {
            r.push([]);
        }
        r[r.length - 1].push(o);
        return r;
    }, []);
    
console.log(grouped);

答案 3 :(得分:0)

您可以仅使用https://riketest.squarespace.com/并将其参数用于数组EventHandler<CustomEventArgs>index

actual array