How to combine first element of one array with first element of second array and so on

Viewed 5440

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']
4 Answers

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?

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)

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)

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

Related