LeftN
LeftN

Reputation: 57

Merge Arrays in Javascript / Node.js

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?

Upvotes: 0

Views: 1235

Answers (5)

Renato Gama
Renato Gama

Reputation: 16519

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

Upvotes: 2

Ele
Ele

Reputation: 33726

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

Upvotes: 2

sumit
sumit

Reputation: 15464

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

Upvotes: 1

Milan Adamovsky
Milan Adamovsky

Reputation: 1579

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.

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 370689

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

Upvotes: 2

Related Questions