Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge two arrays in JavaScript and keep their order

I had an whiteboard task that stumped me in the interview, however I have written a solution and wondered if anyone has improvements on it as I'm iterating which the interviewer said not to. The two arrays must be merged with the order being array1[0], array2[0], array1[1], array2[1]... (see expectedResult) etc

const options = [[1, 12, 5], ["a", "b", "c", "d", "e"]]
const expectedResult = [1, "a", 12, "b", 5, "c", "d", "e"]

function mergeArrays(first, second) {
  let returnArray = []
  
  first.forEach((value, key) => {
    returnArray.push(value)
    if (second[key]) returnArray.push(second[key])
    if (!first[key + 1] && second[key + 1]) {
      returnArray.push(
        ...second.slice(key + 1, second.length)
      )
    }
  })
  return returnArray
}

const result = mergeArrays(options[0], options[1])
console.log(result.toString() === expectedResult.toString(), result)
like image 829
azz0r Avatar asked Jan 12 '17 08:01

azz0r


3 Answers

With reduce (as an alternative to the classical for/while loop control structures)

const options = [[1, 12, 5], ["a", "b", "c", "d", "e"]];
const expectedResult = [1, "a", 12, "b", 5, "c", "d", "e"]

// a is the accumulator
// cV, cI are resp. current value and current index
result = options[0].reduce(function (a, cV, cI) {
    return a.concat([cV,options[1][cI]]);
},[]);


result = result.concat(options[1].splice(options[0].length));
console.log(result.toString() === expectedResult.toString(), result)

At each step two elements are added to the accumulator array a using concat.

like image 107
user2314737 Avatar answered Sep 26 '22 13:09

user2314737


I go the classic way, with a while loop, because it minimize the checks inside of the loop and appends without another check just the rest of one of the arrays.

function mergeArrays(first, second) {
    var min = Math.min(first.length, second.length),
        i = 0,
        result = [];

    while (i < min) {
        result.push(first[i], second[i]);
        ++i;
    }
    return result.concat(first.slice(min), second.slice(min));
}

const options = [[1, 12, 5], ["a", "b", "c", "d", "e"]];

console.log(mergeArrays(...options));
.as-console-wrapper { max-height: 100% !important; top: 0; }
like image 25
Nina Scholz Avatar answered Sep 26 '22 13:09

Nina Scholz


Instead of using value in if conditions , check for length of array.

Problems I see in code are at conditions

   if (second[key]) returnArray.push(second[key])
   // will not run if second[key] is 0,null,undefined.
   if (!first[key + 1] && second[key + 1]) 
   // will produce unwanted result if value reference is 0,null,undefined.

so instead, check for length would produce better result So the condition

    if (second[key]) returnArray.push(second[key]) 

can be changed into

   if( second.length > key) returnArray.push(second[key]) 
like image 31
user1536841 Avatar answered Sep 22 '22 13:09

user1536841