繁体   English   中英

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

[英]Get common data from multiple arrays of object that containing a unique id and nested array using javascript es6

我试图从包含唯一 id(mongoose 对象 id)和字符串数组的多个对象数组中查找公共数据。

例如:

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"]
        }]

输出应在数组中具有最大公共日期的最大公共值,并且该日期应具有最大公共小时。

所以示例输出应该是这样的。

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

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

 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游乐场

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM