There are currently no frequently asked questions associated with this exercise – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this exercise. Ask or answer a question by clicking reply () below.
If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this exercise, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.
Join the Discussion. Help a fellow learner on their journey.
Ask or answer a question about this exercise by clicking reply () below!
You can also find further discussion and get answers to your questions over in Language Help.
Agree with a comment or answer? Like () to up-vote the contribution!
while (leftArray.length > 0 && rightArray.length > 0)
" Because the while loop continues until either leftArray or rightArray is empty, …"
This contradicts itself. The while loop goes until BOTH are empty. I tried this without the concat because it seems like it should be useless if the condition is that BOTH left and right are empty. seems like it should be || (or).
In this case the “and” operator && is doing exactly what you suggest it should. The code inside a while loop repeats as long as the condition evaluates to truthy. If either array has a length that isn’t greater than zero, the condition evaluates to falsy, and control is passed to whatever comes after the loop. Were you to change it to ||, then the loop would continue to iterate until both arrays are empty.
After finishing the exercise below and passing it, the output of the code was: [ 2, 3, 5, 4, 90, 7 ].
I thought the ‘90’ was suppose to be the last element in the list since it is the greatest number. So am I missing something or is there something else?
I guess you could do the merge using || instead of &&
so that you’d have while (leftArray.length > 0 || rightArray.length > 0) {
but you’d have to do something to deal with the case of either of the lengths being 0,
so that all the elements of are added to sortedArray even if one of the arrays is empty.
If you’d do that, then you wouldn’t need the .concat at the end.
const merge = (leftArray, rightArray) => {
const sortedArray = [];
while (leftArray.length != 0 || rightArray.length != 0) {
if (leftArray.length == 0) {
sortedArray.push(rightArray.shift()); // .shift() removes element at [0] and returns it
}
else if (rightArray.length == 0 || leftArray[0] < rightArray[0]) {
sortedArray.push(leftArray.shift()); // .shift() returns element at [0] after removing it
}
else {
sortedArray.push(rightArray.shift()); // .shift() returns element at [0] after removing it
}
}
return sortedArray;
}