-1

I would like to combine two different arrays into one array based on the position of the items inside them.

The array I have now:

var firstName = {'John','Joe','Kees'};
var lastName = {'Smith','Fisherman','Cow'};

The result I would like to have:

var name = {'John Smith', 'Joe Fisherman', 'Kees Cow'};
Mureinik
  • 297,002
  • 52
  • 306
  • 350
Tom Roskam
  • 23
  • 5
  • What you're trying to do is like zipping the arrays. Maybe this question can put you on the right path: https://stackoverflow.com/questions/22015684/how-do-i-zip-two-arrays-in-javascript Or a bit simpler is iterating over 1 array while adding the values of the second array by index, which should work if the arrays have the same length: https://stackoverflow.com/questions/34076624/combine-same-index-objects-of-two-arrays – fravolt Apr 22 '21 at 08:33
  • You are showing object but not array. Are you sure it's object/array ? – Dipak Telangre Apr 22 '21 at 08:37

3 Answers3

1

Array.prototypr.map has a overloaded variant that gets both the value and the index of each value while iterating. You could use it to match each value of firstName to the corresponding lastName:

var firstName = ['John','Joe','Kees'];
var lastName = ['Smith','Fisherman','Cow'];

var name = firstName.map((value, index) => value + ' ' + lastName[index]);

console.log(name);
Mureinik
  • 297,002
  • 52
  • 306
  • 350
0

We can use Array#map to map between the two given arrays.

In each map iteration, take the firstName f from the first array and its corresponding index i and use it to get the full name by combining the firstName and the lastName from the index i:

var firstName = ['John','Joe','Kees'];
var lastName = ['Smith','Fisherman','Cow'];

const combine = (firstName, lastName) => {
  return firstName.map((f, i) => `${f} ${lastName[i] || ""}`);
}

console.log(combine(firstName, lastName));
Fullstack Guy
  • 16,368
  • 3
  • 29
  • 44
0

I made this one. But it is not memory or time efficient. You can make faster version with for loop.

Good luck.

let firstName = ['John','Joe','Kees'];
let lastName = ['Smith','Fisherman','Cow'];


const combiner = (firstArray, secondArray) => Array(Math.max(firstArray.length, secondArray.length)).fill('').map((_, i) => `${firstArray[i] || ''} ${secondArray[i] || ''}`.trim());

// edit: with for loop

const fasterCombiner = (fa, sa) => {
  let result = [], length = fa.length > sa.length ? fa.length : sa.length;
  for(let i = 0; i < length; i++ ) {
    result.push(`${fa[i] || ''} ${sa[i] || ''}`.trim());
  }
  return result;
}
Aykhan Huseyn
  • 94
  • 1
  • 7