I was asked in an interview and my answer was similar to this, which is wrong due to the final loop.
const newSortArrays = (arr1, arr2) => { let output = []; while (arr1.length && arr2.length) { if (arr1[0] < arr2[0]) output.push(arr1[0] < arr2[0] ? arr1.shift() : arr2.shift()) } return [...output, ...arr1, ...arr2] }
Advertisement
Answer
What you are talking about — “sorting” two arrays that are each themselves already sorted — is called a merge. This is how you do that:
function merge( left = [] , right = [] ) { const merged = new Array( left.length + right.length ); let i = 0 ; let j = 0 ; let k = 0 ; // while both lists have items while ( i < left.length && j < right.length ) { const x = left[i]; const y = right[j]; if ( x <= y ) { merged[k++] = x; ++i; } else { merged[k++] = y; ++j; } } // if the left list still has items, take them while ( i < left.length ) { merged[k++] = left[ i++ ]; } // if the right list still has items, take them while ( j < right.length ) { merged[k++] = right[ j++ ]; } return merged; }