In this article, we will cover how to merge two sorted arrays into a single sorted array in JavaScript.
Given there are two sorted arrays, we need to merge them into a single sorted array in JavaScript. We will see the code for each approach along with the output. Below are the possible approaches that will be discussed in this article:
Approaches to merge two sorted arrays into a single sorted array
- Using the concat() and slice() methods in JavaScript
- Using the Array.reduce() and shift() methods in JavaScript
Using the concat() and slice() methods in JavaScript
Here, we are going to basically use the basic concat() and slice() functions of JavaScript that will concat the arrays which we will give as input, and slice() will extract the positions of the arrays given as input.
Example: In this example, we are using concat() and slice() methods in JavaScript
Javascript
// Using concat() and slice() method function mergeSortedArrayUsingConcat(array1, array2) { let sortedArray = [], Array1Index = 0, Array2Index = 0; while ( Array1Index < array1.length && Array2Index < array2.length ) { if ( sortFunc( array1[Array1Index], array2[Array2Index] ) > 0 ) { sortedArray.push(array2[Array2Index++]); } else { sortedArray.push(array1[Array1Index++]); } } if (Array2Index < array2.length) { sortedArray = sortedArray.concat( array2.slice(Array2Index) ); } else { sortedArray = sortedArray.concat( array1.slice(Array1Index) ); } return sortedArray; } function sortFunc(a, b) { return a - b; } console.log( mergeSortedArrayUsingConcat( [1, 2, 3, 5, 9], [4, 6, 7, 8] ) ); |
[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
Using the Array.reduce() method in JavaScript
Here, we will use the reduce() function which is in the Array library. This function is similar to the spread operator as seen in the above approach. reduce(0 function mainly operates on the array and reduces the array to a single value.
Example: In this example, we are going to use Array.reduce() method in JavaScript.
Javascript
//Using Array.reduce() and shift method method function mergeSortedArraysUsingReduce(array1, array2) { // Using array.reduce to generate new sorted array let singleMergedArray = array1.reduce( (outputVar, array1Element) => { while ( array2.length && array2[0] < array1Element ) { outputVar.push(array2.shift()); } outputVar.push(array1Element); return outputVar; }, [] ); return singleMergedArray.concat(array2); } let array1 = [1, 2, 3, 5, 9]; let array2 = [4, 6, 7, 8]; const outputArray = mergeSortedArraysUsingReduce( array1, array2 ); console.log(outputArray); |
[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]