机智的是,我认为我可能对代码视而不见,但无法终生弄清楚是什么原因导致了问题。

理想的结果是,数据数组中的每一行只有一个日期,每个日期有尽可能多的排期。

这适用于第一个项目,但不适用于其他任何项目,最终以重复的日期结束。

我要去哪里错了?

所需数据:
示例中即将到来的数据5个对象,只有两个日期。

["2020-02-20", "LGW"]
["2020-02-20", "LTN"]
["2020-02-20", "LHR"]
["2020-02-26", "LTN"]
["2020-02-26", "LHR"]


两个对象组成的数组(每个日期一个),flights在相应日期对象中按日期排列。

data = [ ["2020-02-20", ["LGW","LTN","LHR"]],
["2020-02-26", ["LTN","LHR"]]
]


下面显示的代码带有注释:

function getRows(alternatives) {
        var data = [];

        for (var i = 0; alternatives.length > i; i++) {
            var tmp = new Date(parseInt(alternatives[i].substring(0, 10)) * 1000);
            var month = (tmp.getMonth() + 1);
            var date = tmp.getFullYear() + "-" + (month < 10 ? "0" + month : month) + "-" + tmp.getDate();
            var airport = alternatives[i].slice(11, 14);

            var rowData = {
                date: date,
                flights: []
            };
            // if data has objects, check to see if the date is in any of the objects, if it isn't then add rowData to data
            if (data.length > 0) {

                for (var j = 0; data.length > j; j++) {

                    if (data[j].date === rowData.date) {
                        //if there are no flights, add the airport, if there are, is the airport already there, if not, add it
                        if (data[j].flights.length > 0 || !data[j].flights.includes(airport)) {
                            data[j].flights.push(airport);
                        }
                    }
                    else {
                        data.push(rowData);
                        continue;
                    }
                }
            }
            else {
                rowData.flights.push(airport);
                data.push(rowData);
            }
        }
        // not working, dupe dates are appearing in the rows
        return data;
    }

最佳答案

您可以使用reduce创建具有日期作为键的对象,其值由具有datearray of flights的数组组成。检查密钥是否已经存在(如果存在),然后仅推入flights数组。



const input = [["2020-02-20", "LGW"],
["2020-02-20", "LTN"],
["2020-02-20", "LHR"],
["2020-02-26", "LTN"],
["2020-02-26", "LHR"]];

const output = Object.values(input.reduce((accu, [date, flight]) => {
    if(!accu[date]) {
        accu[date] = [date, [flight]];
    } else {
        accu[date][1].push(flight);
    }
    return accu;
}, {}));

console.log(output);

09-12 13:48