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

Viewed 99

I am trying to find the common data from multiple arrays of object that contains a unique id (mongoose object id) and an array of string.

for example:

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

The output should have maximum common values in the arrays for maximum common dates and that date should have maximum common hour.

So the sample output should look something like this.

common_data = {
    date: "2021-07-15T12:18:12.223Z",
    time: "30",
    hours: "8:30AM"
}

I looked up at other answers and tried something like this: merged all the arrays and

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
    });
});

but getting error merged_slots_array.shift(...).filter is not a function

1 Answers

After concatenating the arrays, finding the max common hour can be done through a filter that only keeps duplicates, then gets sorted. Once we have that, we can query each array to make sure it contains the max hour, then extract the max date and time. My output was slightly different than yours because i filtered for the max time, hour and date

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

Related