Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging of array in javascript or jquery

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.

like image 378
rohit jaiswal Avatar asked Dec 09 '22 02:12

rohit jaiswal


2 Answers

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
}
like image 160
Tushar Avatar answered Dec 17 '22 08:12

Tushar


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'],'~');
like image 37
Roland Szabo Avatar answered Dec 17 '22 08:12

Roland Szabo