我有一个对象列表,这些对象涉及在不同日期,不同中心发生的事件。我需要获取一个新列表,以显示每个中心的上次活动日期。
列表的结构如下:
var eventsList = [
{id: 1111, centre: "Alpha", date: "01/01/2019", [...Other info]},
{id: 2222, centre: "Alpha", date: "01/02/2019", [...Other info]},
{id: 3333, centre: "Beta", date: "01/01/2019", [...Other info]},
{id: 4444, centre: "Beta", date: "02/01/2019", [...Other info]},
{id: 5555, centre: "Omega", date: "01/03/2019", [...Other info]}]
我想要的结果列表中每个中心只有一个,日期最高,没有其他信息,例如:
var eventsList = [
{centre: "Alpha", date: "01/02/2019"},
{centre: "Beta", date: "02/01/2019"},
{centre: "Omega", date: "01/03/2019"}]
我想出了一种方法,首先将条目存储在一个对象中(以防止重复而不搜索列表),然后从该对象创建最终列表:
var objectList = {};
eventsList.forEach(function (element){
var elementCentre = element.centre;
var elementDate = element.date
if (!objectList.hasOwnProperty(elementCentre) || objectList[elementCentre].date < elementDate) {
objectList[elementCentre] = {centre: elementCentre, date: elementDate}
}
});
return Object.values(objectList);
它有效,但是我不太喜欢它。我不确定这是最好还是最有效的方法。
答案 0 :(得分:1)
您可以使用reduce和Date.parse解析日期并进行比较
var eventsList = [{id: 1111, centre: "Alpha", date: "01/01/2019"},{id: 2222, centre: "Alpha", date: "01/02/2019"},{id: 3333, centre: "Beta", date: "01/01/2019"},{id: 4444, centre: "Beta", date: "02/01/2019"},{id: 5555, centre: "Omega", date: "01/03/2019"}]
let op = eventsList.reduce((op,{centre,date})=>{
if(op[centre]) {
if(Date.parse(date) > Date.parse(op[centre].date)){
op[centre] = {centre,date}
}
} else {
op[centre] = {centre,date}
}
return op
},{})
console.log(op)
答案 1 :(得分:1)
.sort
减去您的日期您可以在Date
调用中减去.sort
个对象,以简单地运行内置的排序方法。
const eventsList = [
{centre: "Alpha", date: "01/02/2019"},
{centre: "Beta", date: "02/01/2019"},
{centre: "Omega", date: "01/03/2019"}]
eventsList.sort((a, b) => new Date(b.date) - new Date(a.date))
console.log(eventsList)
注意:这会eventsList
进行适当排序。为避免进行排序,请尝试以下操作来创建副本然后进行排序:
[...eventsList].sort(/* ... */)
// or
eventsList.slice().sort(/* ... */)
答案 2 :(得分:1)
您可以按照以下步骤进行操作。
centre
和Set()
创建唯一的map()
数组map()
的每个值上使用cents
map()
内部,在filter()
上使用eventLists
,并在其上使用sort()
,并返回第一个元素
var eventsList = [
{id: 1111, centre: "Alpha", date: "01/01/2019"},
{id: 2222, centre: "Alpha", date: "01/02/2019"},
{id: 3333, centre: "Beta", date: "01/01/2019"},
{id: 4444, centre: "Beta", date: "02/01/2019"},
{id: 5555, centre: "Omega", date: "01/03/2019"}]
let cents = [...new Set(eventsList.map(x => x.centre))];
cents = cents.map(x => eventsList.filter(a => a.centre === x).sort((a,b) => new Date(b.date) - new Date(a.date))[0]);
console.log(cents)
答案 3 :(得分:1)
按日期对列表进行排序,然后除去每种类型的第一个事件以外的所有事件。您可以使用单个排序和单个过滤器(其中包含findIndex)来完成此操作:
eventsList.sort((a, b) => new Date(b.date) - new Date(a.date));
eventsList = eventsList.filter((event, index) => {
return index === eventsList.findIndex(ev => event.centre === ev.centre);
});