There is an array of 400 elements, I want to sort them so that the elements in the array were by 4. for example [[1,2,3,4], [a,b,c,d], [true,false,true,false]] and so on ..

tried to implement it like this:

 var arr = [....]// не сортированный массив. var main = []; var secondary = []; for(i=0; i<arr.length; i++){ secondary.push(arr[i]); if(secondary.length === 4){ main.push(secondary); secondary.length = 0; // очищаю чтобы наполнить по новой } } 

But when cleaning the secondary array, it is also cleared in the main .. (after all, if you just push the elements, and after clearing the variable, then the main element is not deleted, unlike the array)

    1 answer 1

    In this case, the reference to the secondary array is saved, so when this object changes, for example, by assigning length , all references point to the new modified value.

    To solve, you just need to assign a new array

     secondary = []; 

    instead

     secondary.length = 0; 
    • works like a clock! thank. It turns out when we push not an array, but single elements, then they are not pushing like links? (for example var x = []; var y = 123; x.push(y); y.length = 0; x will still keep 123 in itself) - Jonny
    • @Jonny, this is all because y , since this number does not have the length property, and in this way y.length = 0 , an attempt is made to add this property, and if you call it in strict mode there will be an error Uncaught TypeError: Cannot create property 'length 'on number and without strict mode assignment is simply ignored. Thus, the variable has not changed, therefore the value in the array should not have changed either, it means everything works as expected. - Grundy
    • understood, thanks for the clarification! - Jonny