3

I have:

array1 = [ "a" , "b" , "c" , "d" ]

array2 = [ 1 ,2 ,3 ]

and the result should be:

matchedArray = [ "a1" , "b2" , "c3"]
Olian04
  • 6,480
  • 2
  • 27
  • 54
  • Try this out: https://stackoverflow.com/a/6717224/1703744 – Marc M. Oct 10 '18 at 20:20
  • Hi Felipe. Welcome to StackOverflow. When posting on StackOverflow, be sure to post a [Minimal, Verifiable, and Complete (MVC)](https://stackoverflow.com/help/mcve) example so we can help you. Always post the code you've tried and where you're having problems so we can provide specific help for you. – samanime Oct 10 '18 at 20:20
  • I don't think either of those linked answers is what they are asking based on the result. – samanime Oct 10 '18 at 20:21

5 Answers5

4

Here's a simple example that should help. Try and optimize it if you can!

array1 = [ "a" , "b" , "c" , "d" ];

array2 = [ 1 ,2 ,3 ];

newArr = [];

for (let i = 0; i < array1.length; i++){
  if (array2[i])
      newArr.push(array1[i]+array2[i]) 
}

console.log(newArr);
samanime
  • 25,408
  • 15
  • 90
  • 139
LawfulGood
  • 177
  • 5
2

It looks like you want to take the string from the same position of both arrays and combine them. If that's the case, something like this should do the trick.

const a = ['a', 'b', 'c'];
const b = [1, 2, 3, 4];

function combine(a, b) {
  const result = [];
  
  // Use both lengths and || to handle uneven arrays
  for(var i = 0; i < a.length || i < b.length; i++) {
    if (a[i] && b[i]) { // make sure they both have values
      result[i] = a[i] + b[i];
    }
  }
  
  return result;
}

console.log(combine(a, b));
samanime
  • 25,408
  • 15
  • 90
  • 139
1

I think what you're looking for is the map function :

let a = ["a", "b", "c", "d"];
let b = [1, 2, 3, 4, 5];
let shorterArray = a.length > b.length ? b : a;
let longerArray = b.length > a.length ? b : a;
let c = shorterArray.map((c, index) => (longerArray === a) ? longerArray[index] + c : c + longerArray[index]);
console.log(c);
//returns ["a1", "b2", "c3"]
John Krakov
  • 355
  • 1
  • 8
0

You could take the minimum length of the arrays and map the values by reducing the arrays.

var array1 = ["a", "b", "c", "d"],
    array2 = [1, 2, 3],
    data = [array1, array2],
    min = Math.min(...data.map(({ length }) => length)),
    result = data.reduce((r, a) => a.slice(0, min).map((v, i) => (r[i] || '') + v), []);
    
console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

Easly, you'll iterate through the one and add it to the other like so.

array1 = [ "a" , "b" , "c" , "d" ];

array2 = [ 1 ,2 ,3 ];

newArray = array2.map((number, index) => {
    return array1[index] + number;
});
Akxe
  • 9,694
  • 3
  • 36
  • 71