3

I am having two arrays.

the first array contains dates

['2020-03-17,2020-03-19,2020-03-18,2020-03-12']

the second array contains time this array consists of time slot of two hours.

['11:00', '13:00','15:00', '17:00','19:00', '21:00', '23:00']

finally, I need the result to look like this:

['2020-03-17,11:00,13:00','2020-03-19,15:00,17:00','2020-03-18,19:00,21:00']
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
Tony Zhao
  • 71
  • 1
  • 7
  • 4
    Welcome to Stack Overflow! Please take the [tour](/tour) (you get a badge!) and read through the [help center](https://stackoverflow.com/help), in particular [How do I ask a good question?](/help/how-to-ask) Your best bet here is to do your research, [search](/help/searching) for related topics on SO, and give it a go. If you get stuck and can't get unstuck after doing more research and searching, post a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) of your attempt and say specifically where you're stuck. People will be glad to help. – palaѕн Mar 19 '20 at 11:07
  • what is the connection point between two array ? – prasanth Mar 19 '20 at 11:08
  • 1
    @prasanth each pair of times goes with a date – Ja͢ck Mar 19 '20 at 11:09
  • 2
    but `2020-03-12` from 1st array is not there in the expected result. what is the logic for that? – palaѕн Mar 19 '20 at 11:11
  • 1
    @palaѕн because there are only 3 pairs of times, the last element in that array doesn't form a pair – Ja͢ck Mar 19 '20 at 11:11
  • Yes you're right @jack. the last element which does'nt form any pair should be excluded in new result – Tony Zhao Mar 19 '20 at 11:14
  • Is the first array supposed to be like that? It's currently holding a single string element containing multiple dates. Shouldn't each date be its own string? – 3limin4t0r Mar 19 '20 at 11:24

4 Answers4

5

Pairing Arrays

If both arrays are in order and every pair of time is associated with a date, you can multiply the date index by 2 to get the first time, then add one to get the ending time.

let dates = ['2020-03-17', '2020-03-19', '2020-03-18', '2020-03-12']
let times = ['11:00', '13:00', '15:00', '17:00', '19:00', '21:00', '23:00']

let dateTime = [];

for (let i in dates) {

  let timeIndex = i * 2;
  let startTime = times[timeIndex]
  let endTime = times[timeIndex + 1]

  if (endTime)
    dateTime.push( [dates[i], startTime, endTime].join(',') )
}

console.log(dateTime)

Note

The data in the OP had flaws that need to be addressed or corrected:

  1. The date array was one string. This answer corrects that by making each date a separate element. If that is not the case, simply extract the dats and split on the comma (i.e., dates.pop().split(','))
  2. The description was that each date has a pair of times, but it is questionable if that is always the case. The last date indicates it only has one associated time. (see update)
  3. If the timing pair occurs often, consider a more functional approach as offered in Jack's answer: https://stackoverflow.com/a/60756349/10408280

Update

  1. Comments revealed that if the last date does not have two times, it is excluded from the results. This answer has been updated to accommodate that instruction; however, this leaves a question concerning data quality.

    What happens if times are missing for internal dates?

Mike
  • 1,279
  • 7
  • 18
5

Let's break this down for a bit; the first thing to do is to define a function that returns pairs of items from an array, like this:

function timePairs(times)
{
    const result = []
    // i gets incremented by two each time, so make sure there are enough items
    // to pick
    for (let i = 0, n = times.length; i + 2 <= n; i += 2) {
        result.push([times[i], times[i + 1]])
    }
    return result
}

The resulting array would look like this:

[['11:00', '13:00'], ['15:00', '17:00'], ['19:00', '21:00']]

Then, each pair should be matched by a date; this can be accomplished by using a zip operation, which can be implemented using .map()

The map operation takes a function that gets called for each item, and it's expected to return the new value.

timePairs(times).map((pair, index) => {
  return [dates[index], ...pair].join(',')
});

We use a small trick above; instead of writing [dates[index], pair[0], pair[1]], it uses the ... operator to shorten the code.

All together, it looks like this:

const dates = ['2020-03-17','2020-03-19','2020-03-18','2020-03-12']
const times = ['11:00', '13:00','15:00', '17:00','19:00', '21:00', '23:00'];

function timePairs(times)
{
  const result = []
  for (let i = 0, n = times.length; i + 1 < n; i += 2) {
    result.push([times[i], times[i + 1]])
  }
  return result
}

const result = timePairs(times).map((pair, index) => {
  return [dates[index], ...pair].join(',')
});

console.log(result);

Faster!

You can do this with a single loop as well, just keep two pointers for dates & pairs:

const dates = ['2020-03-17','2020-03-19','2020-03-18','2020-03-12']
const times = ['11:00', '13:00','15:00', '17:00','19:00', '21:00', '23:00'];

result = []
for (let i = 0, j = 0, n = times.length >> 1; i != n; i++, j += 2) {
  result.push(dates[i] + ',' + times[j] + ',' + times[j + 1])
}
console.log(result)
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
  • Withdrew comment and referred to your answer in mine. Hope that's okay – Mike Mar 19 '20 at 11:51
  • Is there any way to compare two arrays like [2020-03-19, 12:30,14:00] and [2020-03-19, 12:00,14:00] and the result should be true, but as of now it is not a match but contains the similar time. – Tony Zhao Mar 20 '20 at 06:56
  • @TonyZhao how should that comparison take place? what are you trying to do? – Ja͢ck Mar 20 '20 at 07:05
  • Say one user is attending an event of two hrs on a date say 2020-03-19 at start time 10:00 and end time 12:00. and another user want to add in an event on same date but time is 10:30 to 12:30. but first user is already busy in another event that time. so system must say that first user is not available in your selected date and time. – Tony Zhao Mar 20 '20 at 07:22
  • You'd have to detect time overlaps, by sorting on first time ... then iterate over the array, and stop when previous and current overlap – Ja͢ck Mar 20 '20 at 14:46
1

let array1 = ['2020-03-17,2020-03-19,2020-03-18,2020-03-12'];
array1 = array1.join().split(',');
const array2 = ['11:00', '13:00', '15:00', '17:00', '19:00', '21:00', '23:00'];

const merge = []
let index2 = 0;
for (let i = 0; i < array1.length; i++) {
  if (array2[index2 + 1]) {
    merge.push(array1[i] + ',' + array2[index2] + ',' + array2[index2 + 1])
  }
  index2 += 2;
}
console.log(merge)
EugenSunic
  • 13,162
  • 13
  • 64
  • 86
1

Use forEach on dates array and combine elements from times array.

const dates = ["2020-03-17", "2020-03-19", "2020-03-18"];
const times = ["11:00", "13:00", "15:00", "17:00", "19:00", "21:00"];

const merge = (dates, times) => {
  const res = [];
  dates.forEach((date, i) =>
    res.push(`${date},${times[i * 2]},${times[i * 2 + 1]}`)
  );
  return res;
};

console.log(merge(dates, times));
Siva K V
  • 10,561
  • 2
  • 16
  • 29