How to use the concat() and slice() methods in JavaScript 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
// 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]
)
);
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