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?

5
  • yes.. there is a way Commented Mar 28, 2018 at 22:32
  • @MladenIlić, OP is asking for a way to merge elements, not how to concat. Commented Mar 28, 2018 at 22:33
  • Yeah, yeah, my bad. Commented Mar 28, 2018 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? Commented Mar 28, 2018 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. Commented Mar 28, 2018 at 23:03

5 Answers 5

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);

Sign up to request clarification or add additional context in comments.

2 Comments

What if array1 is bigger?
Then just reverse it, or do a test beforehand.
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);

4 Comments

Some explanation of the code and how/why it works could make this a more useful answer.
@jfriend00 my bad!
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 (80% slower than the best one there). It is creative though.
@jfriend00 :( It's good to know about the performance. for-loops are very fast!
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);

8 Comments

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 have a look here stackoverflow.com/questions/5501581/…
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)
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.
OK, I upvoted now that you've added the second option. In a jsperf, 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.
|
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.

4 Comments

You might want to check the outcome in the question again.
Read the question too quick Updated answer. This answer is with performance in mind (thus the for loop)
Why use a template string instead of just +?
@jfriend00 the reason being in case an item is a number, so we don't accidentally add the values rather than concatenate them.
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

1 Comment

Thanks for pointing it, i fixed it but looks like a messy way. please correct me if I am wrong

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.