如何在JavaScript中合并或拼合多维数组

时间:2018-07-14 21:02:18

标签: javascript arrays

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

if (item == null || empty) {
    setText("");
    setBackground(new Background(new BackgroundFill(Color.WHITE, CornerRadii.EMPTY, Insets.EMPTY)));
} else {

    if(item > 2) {
        setText("Warning");
        setBackground(new Background(new BackgroundFill(Color.YELLOW, CornerRadii.EMPTY, Insets.EMPTY)));
    } else if(item > 4) {
        setText("Danger");
        setBackground(new Background(new BackgroundFill(Color.RED, CornerRadii.EMPTY, Insets.EMPTY)));
    } else {
        setText("OK");
        setBackground(new Background(new BackgroundFill(Color.WHITE, CornerRadii.EMPTY, Insets.EMPTY)));
    }
}

(删除了此处的屏幕截图,因为它无关紧要并且分散了注意力)

2 个答案:

答案 0 :(得分:0)

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

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);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:0)

您可以使用<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="movingBox"> </div>创建映射并将所有值分组,然后只需使用Array.reduce()即可获取所有值的数组。

尝试以下操作:

Object.values()