Introduction
In this lab, we will explore how to merge two sorted arrays into a single sorted array using JavaScript. We will use the spread operator, Array.from(), and the shift() method to efficiently merge the arrays. By the end of this lab, you will have a deeper understanding of how to manipulate arrays in JavaScript.
Instructions for Merging Sorted Arrays in JavaScript
To merge two sorted arrays in JavaScript, follow these steps:
- Open the Terminal/SSH and type
nodeto start practicing coding. - Use the spread operator (
...) to clone both of the given arrays. - Use
Array.from()to create an array of the appropriate length based on the given arrays. - Use
Array.prototype.shift()to populate the newly created array from the removed elements of the cloned arrays.
Here's an example code snippet to merge two sorted arrays:
const mergeSortedArrays = (a, b) => {
const _a = [...a],
_b = [...b];
return Array.from({ length: _a.length + _b.length }, () => {
if (!_a.length) return _b.shift();
else if (!_b.length) return _a.shift();
else return _a[0] > _b[0] ? _b.shift() : _a.shift();
});
};
console.log(mergeSortedArrays([1, 4, 5], [2, 3, 6])); // Output: [1, 2, 3, 4, 5, 6]
In the above code, mergeSortedArrays function takes two sorted arrays as arguments and returns the merged array by following the above steps. The output for the example code is [1, 2, 3, 4, 5, 6].
Summary
Congratulations! You have completed the Merge Sorted Arrays lab. You can practice more labs in LabEx to improve your skills.