Why I am not getting complete array after concatenation of two arrays?

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.

@colinthornton , thanks for the response but will you advise how can I modify instead of creating a new array. As I’m new to javascript please advise.

You can use the assignment operator just as with a regular variable.

const myArray = [1, 2, 3, 0, 0, 0];
myArray[3] = "a";
myArray[4] = "b";
myArray[5] = "c";
console.log(myArray); // [1, 2, 3, "a", "b", "c"]
1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.