gpt4 book ai didi

javascript - 如果日期匹配,则将数组对象过滤为另一个数组对象

转载 作者:行者123 更新时间:2023-12-04 10:51:59 25 4
gpt4 key购买 nike

我有一个这样的数组:

array = [
{ team: arsenal, date: "2019-12-21T12:30:00Z" },
{ team: mancity, date: "2019-12-21T12:30:00Z" },
{ team: chelsea, date: "2019-12-21T12:30:00Z" },
{ team: liverpool, date: "2019-12-22T12:30:00Z" },
{ team: spurs, date: "2019-12-22T12:30:00Z" }
];

我想创建其他具有相同日期的数组对象,如下所示:
 array1 = [
{ team: arsenal, date: "2019-12-21T12:30:00Z" },
{ team: mancity, date: "2019-12-21T12:30:00Z" },
{ team: chelsea, date: "2019-12-21T12:30:00Z" },
];

array2 = [
{ team: liverpool, date: "2019-12-22T12:30:00Z" },
{ team: spurs, date: "2019-12-22T12:30:00Z" }
];

我正在使用 vue.js,但我想这只是简单的 javascript 解决方案。我试过 filter 和 for 循环,我不断收到错误。也许 lodash 有解决方案?什么是最优雅的。

我的尝试:
arrayFilter() {
for (var i = 0, dates = array.length; i < dates; i++) {
var datearray = [];
array.map((item, i) => {
if (array[i] === item.date) {
datearray.push(item.date);
}
console.log("datearray: ", datearray);
});
}
}

最佳答案

基本上,您不需要任何库。只需使用 reduce ()。

const array = [
{ team: 'arsenal', date: "2019-12-21T12:30:00Z" },
{ team: 'mancity', date: "2019-12-21T12:30:00Z" },
{ team: 'chelsea', date: "2019-12-21T12:30:00Z" },
{ team: 'liverpool', date: "2019-12-22T12:30:00Z" },
{ team: 'spurs', date: "2019-12-22T12:30:00Z" }
]

const grouppedObjectByDate = array.reduce((acc, item) => {
(acc[item.date] || (acc[item.date] = [])).push(item)
return acc
}, {})

console.log(grouppedObjectByDate)
// {
// "2019-12-21T12:30:00Z": [
// {"team": "arsenal", "date": "2019-12-21T12:30:00Z"},
// {"team": "mancity", "date": "2019-12-21T12:30:00Z"},
// {"team": "chelsea", "date": "2019-12-21T12:30:00Z"}
// ],
// "2019-12-22T12:30:00Z": [
// {"team": "liverpool", "date": "2019-12-22T12:30:00Z"},
// {"team": "spurs", "date": "2019-12-22T12:30:00Z"}
// ]
// }

console.log(Object.values(grouppedObjectByDate))
// [
// [
// {"team": "arsenal", "date": "2019-12-21T12:30:00Z"},
// {"team": "mancity", "date": "2019-12-21T12:30:00Z"},
// {"team": "chelsea", "date": "2019-12-21T12:30:00Z"}
// ],
// [
// {"team": "liverpool", "date": "2019-12-22T12:30:00Z"},
// {"team": "spurs", "date": "2019-12-22T12:30:00Z"}
// ]
// ]

关于javascript - 如果日期匹配,则将数组对象过滤为另一个数组对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59435857/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com