gpt4 book ai didi

javascript - 使用javascript es6从包含唯一ID和嵌套数组的多个对象数组中获取公共(public)数据

转载 作者:行者123 更新时间:2023-12-04 07:22:44 27 4
gpt4 key购买 nike

我正在尝试从包含唯一 id( Mongoose 对象 id)和字符串数组的多个对象数组中查找公共(public)数据。
例如:

array1 = [{
_id: "60f027f98b55eb2df1f36c04",
date: "2021-07-15T12:18:12.223Z",
time: "30",
hours: ["8:00 AM", "8:30 AM"]
}]
array2 = [{
_id: "60f027f98b55eb2df1f36c05",
date: "2021-07-15T12:18:12.223Z",
time: "60",
hours: ["7:30 AM", "8:30 AM", "9:30AM"]
}]
array3 = [{
_id: "60f027f98b55eb2df1f36c06",
date: "2021-07-16T12:12:12.223Z",
time: "30",
hours: ["7:00 AM", "8:30 AM"]
}]
输出应该在数组中具有最大公共(public)日期的最大公共(public)值,并且该日期应该具有最大公共(public)时间。
所以示例输出应该看起来像这样。
common_data = {
date: "2021-07-15T12:18:12.223Z",
time: "30",
hours: "8:30AM"
}
我查看了其他答案并尝试了这样的事情:
合并所有数组和
let result = merged_slots_array.shift().filter(function(v) {
return merged_slots_array.every(function(a) {
const matchDate = a.date === v.date;
const getMatchTime = a.hours.shift().filter(function(x) {
return v.hours.every(function(t) {
return x.indexOf(t) !== -1;
})
});
return matchDate && getMatchTime
});
});
但出现错误 merged_slots_array.shift(...).filter is not a function

最佳答案

连接数组后,可以通过只保留重复项的过滤器来查找最大公共(public)时间,然后对其进行排序。一旦我们有了它,我们就可以查询每个数组以确保它包含最大小时数,然后提取最大日期和时间。我的输出与您的略有不同,因为我过滤了最大时间、小时和日期

array1 = [{
_id: "60f027f98b55eb2df1f36c04",
date: "2021-07-15T12:18:12.223Z",
time: "30",
hours: ["8:00 AM", "8:30 AM"]
}]
array2 = [{
_id: "60f027f98b55eb2df1f36c05",
date: "2021-07-15T12:18:12.223Z",
time: "60",
hours: ["7:30 AM", "8:30 AM", "9:30AM"]
}]
array3 = [{
_id: "60f027f98b55eb2df1f36c06",
date: "2021-07-16T12:12:12.223Z",
time: "30",
hours: ["7:00 AM", "8:30 AM"]
}]

const getCommon = (arrays) => {
let group = [].concat.apply([], [...arrays])
let hour = group.map(e=>e.hours).flat().filter((e,i,a) => a.indexOf(e) !== i).sort((a,b) => a.localeCompare(b))[0]
let common = group.filter(e=>e.hours.includes(hour))
let time = Math.max(...common.map(e => +e.time))
let date = common.map(e => e.date).sort((a,b) => new Date(b) - new Date(a))[0];
return {date: date, time: time, hours: [hour]}
}
let arg = []
arg.push(array1)
arg.push(array2)
arg.push(array3)
console.log(getCommon(arg))

TS Playground

关于javascript - 使用javascript es6从包含唯一ID和嵌套数组的多个对象数组中获取公共(public)数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68395318/

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