I have:
array1 = [ "a" , "b" , "c" , "d" ]
array2 = [ 1 ,2 ,3 ]
and the result should be:
matchedArray = [ "a1" , "b2" , "c3"]
I have:
array1 = [ "a" , "b" , "c" , "d" ]
array2 = [ 1 ,2 ,3 ]
and the result should be:
matchedArray = [ "a1" , "b2" , "c3"]
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);
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));
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"]
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);
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;
});