0
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 .....

3
  • i know other ways to get it as expected, but i dont know why its not working in this way, thanks in advance for the explaination Commented Nov 27, 2022 at 16:54
  • If I understand your problem right, you need to remove the continue statement. Commented Nov 27, 2022 at 16:57
  • if( !test.has(EI)) should be if( !test.has(EI.age)){ Commented Nov 27, 2022 at 17:04

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

You also can use test.set(EI.age,(test.get(EI.age) | []).push(EI) ); and remove first if statement at all
0

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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.