I am trying to solve Array question on leetcode Array Merge Sort and issue is that when I am running my code in online compiler i.e. JS Fiddle, Programiz, I can see the complete array after concatenation but when I am running same code on leetcode compiler getting only first array instead of complete array.
Why return is not working here and when I am checking with console it shows the correct answer? It seems, I’m missing something please help me on this.
Below is my code -
var merge = function(nums1, m, nums2, n) {
let x = nums1.length;
if(x !== m){
for(let i = x; i > m; i--){
nums1.pop(nums1[i]);
}
}
return nums1.concat(nums2).sort((a,b)=> a -b);
};
console.log(merge([1,2,3,0,0,0],3,[2,5,6],3));
Here’s the starter code when you select JavaScript
/**
* @param {number[]} nums1
* @param {number} m
* @param {number[]} nums2
* @param {number} n
* @return {void} Do not return anything, modify nums1 in-place instead.
*/
var merge = function(nums1, m, nums2, n) {
};
As it says, you should not return anything. Instead, you should “modify nums1”.
Your problem is that concat() creates a new array, it does not modify nums1.