0

I was wondering if there was a way to merge arrays in this way in javascript

Array1 = ['1', '234', '56']

Array2 = ['1', '2', '45', '56']

Wanted outcome = ['11', '2342', '5645', '56']

Is there a way built into the language to do this?

jfriend00
  • 683,504
  • 96
  • 985
  • 979
LeftN
  • 37
  • 1
  • 5
  • yes.. there is a way – vinayakj Mar 28 '18 at 22:32
  • @MladenIlić, OP is asking for a way to merge elements, not how to concat. – CertainPerformance Mar 28 '18 at 22:33
  • Yeah, yeah, my bad. – Mladen Ilić Mar 28 '18 at 22:33
  • 1
    You can add strings together, and you can iterate over the array with forEach or a for loop. What research have you done? Where's your attempt? –  Mar 28 '18 at 22:34
  • Good questions show that you've done some of your own research, show what you've tried and explain exactly where you got stuck. You should not be using stackoverflow as a "please write this code for me" service. stackoverflow should be used as a problem solving service when you've attempted to solve the problem yourself and you show what you've attempted to do. – jfriend00 Mar 28 '18 at 23:03

5 Answers5

2

Use .map to transform one array into another:

const Array1 = ['1', '234', '56']
const Array2 = ['1', '2', '45', '56'];
const merged = Array2.map((arr2elm, i) => (Array1[i] ? Array1[i] : '') + arr2elm);
console.log(merged);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
2

No native feature for that, but here is a way to achieve it;

var a1 = ['1', '234', '56'];
var a2 = ['1', '2', '45', '56'];

var length = Math.max(a1.length, a2.length)
var merge = new Array(length).fill().map((el, index) => {
    return (a1[index] || '') + (a2[index] || '')
})

console.log(merge)

This code will provide you with the correct answer regardless of which array is bigger.

EDIT:

As per commenter suggestion, by using a for loop you wont waste memory resources by creating an array just for iteration purposes.

    var a1 = ['1', '234', '56'];
    var a2 = ['1', '2', '45', '56'];

    var length = Math.max(a1.length, a2.length)
    var merge = []
    for (var i = 0; i < length; i++) {
      merge.push((a1[i] || '') + (a2[i] || ''))
    }

    console.log(merge)

And, even faster if you replace the .push() with an assignment:

    var a1 = ['1', '234', '56'];
    var a2 = ['1', '2', '45', '56'];

    var length = Math.max(a1.length, a2.length);
    var merge = new Array(length);
    for (var i = 0; i < length; i++) {
      merge[i] = (a1[i] || '') + (a2[i] || '');
    }

    console.log(merge);
jfriend00
  • 683,504
  • 96
  • 985
  • 979
Renato Gama
  • 16,431
  • 12
  • 58
  • 92
  • Why create an array filled with emptiness, then use `.map()` on it? Might as well just use a `for` loop to populate a new array. – jfriend00 Mar 28 '18 at 23:23
  • @jfriend00 have a look here https://stackoverflow.com/questions/5501581/javascript-new-arrayn-and-array-prototype-map-weirdness – Renato Gama Mar 28 '18 at 23:25
  • Also, I suggest that you remove the call to `.fill()` and experience it yourself. The second option (to use a for loop instead) is in fact a lot better (considering memory consumption) – Renato Gama Mar 28 '18 at 23:26
  • The point is that you're just wasting resources by creating a new array and then calling `.fill()` on it and never using it for anything except as an iterator for `.map()`. I would think it is more efficient to just use a `for` loop with the `length` you already have to do an iteration without ever creating that temporary array at all. From an efficiency point of view, you're creating an array you're never going to use the contents of, then iterating it twice. – jfriend00 Mar 28 '18 at 23:27
  • 1
    The link you referenced has nothing to do with the meaning of my comments. I'm talking about just using `for (let i = 0; i < length; i++)` instead of `new Array(length).fill().map()`. It appears you don't yet understand my comment. – jfriend00 Mar 28 '18 at 23:30
  • I first thought you were questioning why using `fill()`, the link I shared elaborates on that. Using a for loop is indeed better in terms of memory consumption. It is the second time that I agree with you. – Renato Gama Mar 28 '18 at 23:32
  • 2
    OK, I upvoted now that you've added the second option. In [a jsperf](https://jsperf.com/combine-contents-of-arrays), the second option is about 30% faster and if you preallocate the merge array and just assign `merge[i] = (a1[i] || '') + (a2[i] || '')` instead of use `.push()`, then it's about 50% faster. – jfriend00 Mar 28 '18 at 23:38
  • Thank you for you contribution @jfriend00 – Renato Gama Mar 29 '18 at 01:31
2

An alternative using the function Array.from

The function Array.from accepts three params:

  • arrayLike An array-like or iterable object to convert to an array.
  • mapFn Map function to call on every element of the array. Optional.
  • thisArg Value to use as this when executing mapFn Optional.

This approach passes an object with the required property length (array-like or iterable object) with the max length from both arrays and the callback will provide two params:

  • value (in this case is undefined) from an array
  • The current index.

Basically, the callback concatenates two values and both operands check for the current value at a specific index because not necessarily the arrays have the same length.

var arr1 = ['1', '234', '56'],
    arr2 = ['1', '2', '45', '56'],
    newArray = Array.from({length: Math.max(arr1.length, arr2.length)}, 
                         (_, i) => ((arr1[i] || '') + (arr2[i] || '')));
//                        ^  ^
//                        |  |
//                        |  +---- This is the current index.
//                        |
//                        +---- In this case, the value is undefined
//                              and is unnecessary to accomplish your
//                              scenario.
console.log(newArray);
Ele
  • 33,468
  • 7
  • 37
  • 75
  • Some explanation of the code and how/why it works could make this a more useful answer. – jfriend00 Mar 28 '18 at 23:20
  • @jfriend00 my bad! – Ele Mar 28 '18 at 23:35
  • Interesting use of `Array.from()`. Never seen that before. FYI, compared to the scenarios in Renato's answer and my comments below it, this solution turns out to be [pretty slow](https://jsperf.com/combine-contents-of-arrays) (80% slower than the best one there). It is creative though. – jfriend00 Mar 29 '18 at 00:17
  • @jfriend00 `:(` It's good to know about the performance. `for-loops` are very fast! – Ele Mar 29 '18 at 00:19
1
function mergeArrays(array1, array2) {
   const count = array1.length > array2.length 
      ? array1.length
      : array2.length;

   const result = [];

   for (let i = 0; i < count; i++) {
      result.push(`${ array1[i] || '' }${ array2[i] || '' }`);
   }

   return result;
}

A side-note: don't use uppercase naming for your identifiers unless they are classes.

Milan Adamovsky
  • 1,519
  • 1
  • 10
  • 5
1

You can do like below

let Array1 = ['1', '234', '56','11','11','22']; 
let Array2 = ['1', '2', '45', '56'];
let new_arr=[];
new_arr=Array1.map((object,i) => object + Array2[i]).concat(Array2.splice(Array1.length,1));
//remove undefined due to variable size
let new_arr_str=new_arr.join(",").replace(/undefined/g,'');
console.log(new_arr_str.split(","));

I have removed undefined variable if array1 is larger than array 1 using string functions

sumit
  • 15,003
  • 12
  • 69
  • 110
  • Thanks for pointing it, i fixed it but looks like a messy way. please correct me if I am wrong – sumit Mar 28 '18 at 23:58