Bluefin zen
Bluefin zen

Reputation: 53

Trying to merge two unsorted arrays in Javascript

I have written code in javascript trying to return a single sorted array by giving two sortedarray inputs.

function finalArray(arr1, arr2) {
  const mergedArray = [];
  if (arr1.length === 0) {
    return arr2;
  }
  if (arr2.length === 0) {
    return arr1;
  }
  let arr1Item = arr1[0];
  let arr2Item = arr2[0];
  let i = 1;
  let j = 1;

  while (arr1Item || arr2Item) {
    if (arr2Item === undefined || arr1Item < arr2Item) {
      mergedArray.push(arr1Item);
      arr1Item = arr1[i];
      i++;
    } else {
      mergedArray.push(arr2Item);
      arr2Item = arr2[j];
      j++;
    }
  }
  return mergedArray
}

console.log(finalArray([2, 6, 4, 10], [15, 1, 5, 33]));

Can anyone help with how to merge unsorted arrays?

Upvotes: 1

Views: 474

Answers (2)

pixelcreated
pixelcreated

Reputation: 196

Merge your two arrays first, then perform the sort?

const arr1 = [2, 6, 4, 10];
const arr2 = [10, 1, 5, 33];
const newArray = ([...arr1, ...arr2]);
newArray.sort(function(a,b){return a - b});
console.log(newArray);

Expected output: [1, 2, 4, 5, 6, 10, 10, 33]

Upvotes: 2

Sadegh Sazmand
Sadegh Sazmand

Reputation: 149

The problem is you are comparing every two pair of data and pushing smaller one. First try to sort each sub array without entering compare process for mixing. After the sub arrays are being sorted, then compare to each other.

Upvotes: 0

Related Questions