user2893258
user2893258

Reputation: 11

Javascript push function doesn't seem to work correctly in code

Problem statement : Clean the room function: Input [1,2,4,591,392,391,2,5,10,2,1,1,1,20,20], make a function that organizes these into individual array that is ordered. For example answer(ArrayFromAbove) should return:

 [[1,1,1,1],[2,2,2], 4,5,10,[20,20], 391, 392,591].

My Code:

const arrNum = [1,2,4,591,392,391,2,5,10,2,1,1,1,20,20] ;

function org(arr) {
    let finalarr = [];
    let arrnew = [];
    let val = 0;
    arr.sort((function(a, b){return a-b}));
    //console.log(arr);
    for (i=0; i<arr.length; i++){
        if (arr[i] != 0) {
            val = arr[i];
            arrnew.length = 0;
            arrnew.push(arr[i]);
            arr[i] = 0;
            for (j=0; j<arr.length; j++){
                if (arr[j] == val && arr[j] != 0) {
                    arrnew.push(arr[j]);
                    arr[j] = 0;
                }
            }
            finalarr.push(arrnew);
            console.log(arrnew);
        }
    }
    return finalarr;
    console.log(finalarr)
}

org(arrNum)

But this doesn't seem to give desired answer : Not sure what I am doing wrong. I have found the other solutions but I need to know what is wrong in my code please.

Upvotes: 0

Views: 236

Answers (1)

Avinash Kumar Singh
Avinash Kumar Singh

Reputation: 457

Objects and arrays are pushed as a pointer to the original object . Built-in primitive types like numbers or booleans are pushed as a copy.

In your code your are pushing arrnew in finalarr

finalarr.push(arrnew);

Which means reference of arrnew is pushed in finalarr.

So after first iteration of for loop:

finalarr = [[1,1,1,1]]
arrnew = [1,1,1,1]

Here element of array finalarr is acutally pointer to array arrnew.

So, In the second iteration the statement

arrnew.length = 0

Will empty the array arrnew, as array finalarr have pointer to array it also gets modified:

finalarr= [[]]

Then inner for loop will push three 2 in array arrnew = [2,2,2], so finalarr become [[2,2,2]].

At the end of second iteration finalarr.push(arrnew); will push one new reference of arrnew in finalarr. So finalarr will become

finalarr = [[2,2,2], [2,2,2]]

So at the end of all iterations, finalarr will have 9 pointers, all pointing to arrnew and the final value in arrnew is [591].

finalarr = [[591],[591],[591],[591],[591],[591],[591],[591],[591]]

You can update you code, just replace arrnew.length = 0 with arrnew = []

Upvotes: 1

Related Questions