Manoj Kumar
Manoj Kumar

Reputation: 27

Concatenate two arrays

how to add two arrays if the condition were,

  1. longer array should be appended to the shorter array.
  2. If both arrays are equally long, the second array should be appended to the first array.

For example: concatUp([1, 2], [3]) should return [3, 1, 2] and concatUp([5, 7], [6, 8]) should return [5, 7, 6, 8].

here is my code:

function concatUp(a1, a2) {
  var list = a1,
    a2;
  var arrLen1 = a1.length;
  var arrLen2 = a2.length;
  if (a1 > a2) {
    a2.concat(a1);
  } else if (a1 < a2) {
    a1.concat(a2);
  } else {
    a1.push(a2);
  }
  return list;
}
console.log(concatUp([1, 2], [3]));
console.log(concatUp([5, 7], [6, 8]));

Upvotes: 1

Views: 836

Answers (1)

Sven.hig
Sven.hig

Reputation: 4519

probably you want something like this

function concatUp(arr1,arr2){
  return arr1.length>arr2.length ?[...arr2,...arr1]:[...arr1,...arr2]
}

console.log(concatUp([1, 2], [3]));
console.log(concatUp([5, 7], [6, 8]))

Upvotes: 1

Related Questions