var first = [ "a", "b", "c" ];
var second = [ "d", "e", "f" ];
My output should be
var final=["a~d","b~e","c~f"];
where '~' is delimiter.
Check if the length
of both arrays.
See comments inline in the code:
var first = [ "a", "b", "c" ];
var second = [ "d", "e", "f" ];
var len = first.length > second.length ? first.length : second.length;
// Get the length of the array having max elements
var separator = '~';
var final = [];
for(var i = 0; i < len; i++) {
// If no element is present, use empty string
first[i] = first[i] ? first[i] : '';
second[i] = second[i] ? second[i] : '';
final.push(first[i] + separator + second[i]);
// Add the new element in the new array
}
Here is a function for this... you can specify the behavior, if the arrays are not the same length:
function merge(arr1,arr2,delimiter){
var i,len;
var delim = delimiter.toString();
var res = [];
if(arr1.length !== arr2.length){
//TODO: if arrays have different length
}else{
len = arr1.length;
for(i=0; i< len; i++){
res[i] = arr1[i] + delim + arr2[i];
}
}
return res;
}
merge(['a','b','c'],['d','e','f'],'~');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With