How to use the Array.reduce() method in JavaScript 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.
//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);
Output
[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
JavaScript Program to Merge two Sorted Arrays into a Single Sorted Array
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
Table of Content
- Using the concat() and slice() methods in JavaScript
- Using the Array.reduce() method in JavaScript
- Using Two Pointers
Contact Us