Home > Enterprise >  Javascript array that inside of map appears empty
Javascript array that inside of map appears empty

Time:11-28

let arr1 =[{name:'mani',age:2},{name:'raj',age:2},{name:'s',age:1}];

let test = new Map();

for(const EI of arr1){

    if( !test.has(EI.age)){
        test.set(EI.age,new Array());
     
    }
    
    test.set(EI.age,test.get(EI.age).push(EI) );
     
}

when i console log this map, the array is empty for all the keys.

but it works as expected for the below code

let arr1 =[3,4,5,6,6,7,8,8,8];

let test = new Map();

for(const EI of arr1){

    if( !test.has(EI)){
        test.set(EI,1);
        continue;
    }

    test.set(EI,test.get(EI)   1);

}

Even i tried taking copy of array test.set(EI,[test.get(EI)].push(1) ) still get empty array only

here the result is as expected

array is empty here .....

CodePudding user response:

push returns the length, not the array.

so after this call:

test.set(EI.age,test.get(EI.age).push(EI) );

The map entry for EI.age isn’t an array. It’s a number.

And I would expect subsequent push calls for that entry to error.

And unless it’s your intention to skip the first occurrence you should remove the continue after creating the empty array.

CodePudding user response:

From what I understand seeing your code, you're trying to have test object with keys being the age and value being an array of whosoever is of that age. This should work for that case :

let arr1 =[{name:'mani',age:2},{name:'raj',age:2},{name:'s',age:1}];

let test = {};

for(const EI of arr1){
    if(!test[EI.age]){
        test[EI.age] =  [];
    }
    
    test[EI.age].push(EI.name);
     // Or optionally, push the whole object instead
     // test[EI.age].push(EI);
}
  • Related