Click here to Skip to main content
15,881,852 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
If i put var right on the bottom of the left variable , it returns empty string but it works fine when i declare it before left.

Why?

What I have tried:

<pre>let list = [1,3,5,2,9,4,6,7]

function mergeSort(list){
  if (list.length<2){
    return list
  }
  console.log(list);
  let mid =Math.floor((list.length)/2) ;
  console.log(mid);
   var right = list.splice(mid);
  var left = list.splice(0,mid); 


  
  console.log(left,right);
  return merge(mergeSort(left),mergeSort(right));

 
}
function merge(left,right){
let array= []
while(left.length && right.length){
  if (left[0]<right[0]){
  array.push(left.shift())
}
else {
  array.push(right.shift())
}
}
return [...array,...left ,...right]
}
console.log(mergeSort(list));
Posted
Updated 28-Jan-23 18:50pm

1 solution

If in doubt, read the documentation: JavaScript Array splice() Method[^]
There you will find the cause of your problem:
Quote:
The splice() method overwrites the original array.

A quick test proves that:
HTML
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Arrays</h2>

<p>The Array.splice() method adds and removes array elements:</p>

<p id="demo"></p>
<p id="left"></p>
<p id="right"></p>

<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits;
let mid = Math.floor((fruits.length)/2) ;
var right = fruits.splice(mid);
document.getElementById("right").innerHTML = fruits;
var left = fruits.splice(0, mid); 
document.getElementById("left").innerHTML = fruits;
</script>
</body>
</html>
 
Share this answer
 
Comments
Richard Deeming 30-Jan-23 4:51am    
And the MDN documentation[^] even points to the solution:
To access part of an array without modifying it, see slice()[^].

:)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900