比较两个数组的相交值 [英] comparing two arrays for intersecting values

查看:68
本文介绍了比较两个数组的相交值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用JavaScript比较两个不同的数组并测试相交的值。

I'm trying to use JavaScript to compare 2 different arrays and test for intersecting values.

该数组包含每周7天的可用性时间范围。在 availability 数组下方,每个键代表从星期日开始的一周中的某一天。因此,键0 =星期日,键1 =星期一.....最大键数为6,即=星期六

This array contains ranges of times of availability for a 7 day week. In the availability array below each key represents a day of the week starting with Sunday. So key 0 = Sunday, key 1 = Monday..... maximum number of keys would be 6 which = Saturday

var availability = [["8:30AM-12PM","2PM-6PM"],
["6:15AM-9:30AM","1PM-4PM","8PM-11:15PM"],[],["9AM-9PM"]];

以下数组 need1 包含时间范围一周中特定日期的需求(从周日{key0}到周六{key6}的任何地方)。它使用与上述 availability 数组相同的密钥格式。 need1 数组应在 availability 数组中列出的时间和日期内匹配。因此,在将需要1 可用性进行比较时,应该找到一个匹配项。

The below array need1 contains ranges of times of need for specific days throughout the week (anywhere from Sunday{key0} to Saturday{key6}). It uses the same key format as the above availability array. need1 array should match within the times and days listed in the availability array. So when comparing need1 to availability a match should be found.

var need1 = [["9AM-11:30AM","3PM-5PM"],[],[],["2PM-6:30PM"]]; //matches

下面的数组 need2 是不匹配的示例,因为需求时间范围不在可用性数组中列出的时间和天数范围内。因此,在将需要2 可用性进行比较时,找不到匹配项。

The below array need2 is an example of an non-match, since the times of need ranges are outside the ranges of times and days listed in the availability array. So when comparing need2 to availability NO match should be found.

var need2 = [["7:30AM-11:30AM"],[],[],["2PM-6:30PM", "8PM-10:30PM"]]; //does not match

我试图弄清楚如何比较这两个数组以进行匹配需要范围与可用性范围。这意味着需求范围必须完全适合每天的可用性范围。比较时,我要寻找的只是一个简单的true或false值。 true =匹配, false =不匹配。但是,我不知道如何有效地做到这一点。任何帮助将不胜感激!

I'm trying to figure out how to compare these 2 arrays to match up the need ranges with the availability ranges. Meaning the need ranges have to completely fit inside the availability ranges for each day. All I'm looking for is a simple true or false returned value when comparing. true = match and false = NOT a match. However, I have no idea how to to efficiently do this. Any help would be appreciated!

此外,如果需要的话,如果可以比较它们,可以用其他格式布置数组值。即使用日期值而不是字符串,或者使用24小时格式而不是12小时格式

Also, If need be I can lay out the array values in a different format if it would make comparing them easier. i.e. using date values instead of strings, or 24 hour format instead of 12 hour format

推荐答案

我要冒险在这里,采取的方法与您开始时的方法略有不同,但这为您的基本问题提供了解决方案:可用时间与所需时间是否匹配?

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?

在提供代码之前,这里有一些建议:

1.在顶层使用对象,而不是数组。使用数组位置有意义是危险的。而是利用JavaScript对象文字的功能。

2.分开开始和结束时间,不要将它们放在同一字符串中。

3.利用本机Array方法的功能。

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 day
  sunday: [ 
    {
      start: '09:45', // has a match
      stop: '12:00'
    },
    {
      start: '14:00', // has a match
      stop: '18:00'
    }

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

const getMinutes = (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;
}

const isTimeMatch = (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;
};

const compareDays = (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));
  });
}

function findMatches(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');
}

这篇关于比较两个数组的相交值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆