Skip to content Skip to sidebar Skip to footer

Comparing Two Arrays For Intersecting Values

I'm trying to use JavaScript to compare 2 different arrays and test for intersecting values. This array contains ranges of times of availability for a 7 day week. In the availabi

Solution 1:

I'm going to take a risk here and take a slightly different approach than you've started with, but which provides a solution to your basic question: are there any matches between the available times and the needed times?

Before I present code, here are some recommendations: 1. Use an Object at the top level, not an array. Using array positions as meaningful is dangerous. Instead utilize the power of JavaScript object literals. 2. Separate your start and stop times, do not put them in the same string. 3. Utilize the power of native Array methods.

I make these recommendations and provide the following code snippet as it seems that you have some wiggle room in how you approach the problem.

UPDATED Changed assumption per request. Only returns match for a given day, if every needed start/time slot finds a matched time slot in the availability object.

Something like the following should get you where you want to go. This will return an object of the matched needs.

/* structure your schedule as objects with arrays of objects of start/stop times */const availability1 = {
  sunday: [
    {
      start: '08:30',
      stop: '12:00'
    },
    {
      start: '14:00',
      stop: '18:00'
    }
  ],
  monday: [{
    start: '06:25',
    stop: '11:45'
  }],
  wednesday: []
};

const need1 = {
  // will be matched, every needed time slot is within an availability slot// on the same daysunday: [ 
    {
      start: '09:45', // has a matchstop: '12:00'
    },
    {
      start: '14:00', // has a matchstop: '18:00'
    }

  ],
  monday: [ // will not be matched because...
    {
      start: '14:00', // has NO matchstop: '16:00'
    },
    {
      start: '07:00', // has a matchstop: '10:00'
    }
  ],
  tuesday: []
};

constgetMinutes = (timeString) => {
  const timeParts = timeString.split(':');
  const hours = Number(timeParts[0]);
  const minutes = Number(timeParts[1]);
  const timeInMinutes = (hours * 60) + minutes;
  // console.log(`timeInMinutes: ${timeInMinutes}`);return timeInMinutes;
}

constisTimeMatch = (availabilityTime, needTime) => {
  
  const availStart = getMinutes(availabilityTime.start);
  const availStop = getMinutes(availabilityTime.stop);
  const needStart = getMinutes(needTime.start);
  const needStop = getMinutes(needTime.stop);
  
  console.log(`Availibility ${availabilityTime.start} (${availStart}) - ${availabilityTime.stop} (${availStop})`)
  console.log(`Need         ${needTime.start} (${needStart}) - ${needTime.stop} (${needStop})`)
  
  const startTimeMatch = availStart <= needStart;
  const stopTimeMatch = availStop >= needStop;
  
  const isMatch = startTimeMatch && stopTimeMatch;
  
  console.log(`is match: ${isMatch}`);
  return isMatch;
};

constcompareDays = (availTimes, needTimes) => {
  return needTimes.map((needTime, i) => {
    
    const matches = availTimes.filter((availTime) => {
      return (isTimeMatch(availTime, needTime));
    });
    
    needTime.match = matches.length > 0;
    return needTime;
  }).filter((needTime, i, allNeedTimes) => {
    return (allNeedTimes.every((i) => i.match === true));
  });
}

functionfindMatches(availability, need) {
  
  const matches = Object.keys(availability).reduce((accumulator, day) => {
    
    if (availability[day] && need[day]) {
      console.log(`Possible matches found on ${day}`)
      const matches = compareDays(availability[day], need[day]);
      if (matches.length > 0) {
        accumulator[day] = matches;
      }
    }
    
    return accumulator;
    
  }, {});
  
  return (Object.keys(matches).length === 0) ?
    false : matches;
}

const matchedTimes = findMatches(availability1, need1);

if (matchedTimes) {
  console.log('The following needs match availability:');
  console.log(matchedTimes);
} else {
  console.log('No matches found');
}

Post a Comment for "Comparing Two Arrays For Intersecting Values"