0

I have array like this

Var arr =[
            ["ali", "classroom1"],
            ["john", "classroom1"],
            ["Doe", "classroom1"],
            ["ahmed", "classroom2"],
            ["Mo", "classroom2"],
            ["Wael", "classroom3"]
           ]
            

Now I want to create arrays or slit it to get array for classroom1 and different array for classroom2 .....

I used splice and map but it seems they're not used for this

Ab817
  • 1
  • 3
  • *I used splice and map but it seems they're not used for this*. Show what you have tried so far... – DecPK Aug 13 '22 at 08:48
  • You can use `forEach`, `reduce` here. All you have to do is loop over `arr` and push elements in new array. – DecPK Aug 13 '22 at 08:49
  • or [Group array items using object](https://stackoverflow.com/questions/31688459/group-array-items-using-object) – pilchard Aug 13 '22 at 09:01

1 Answers1

0

Consider something like this:

let arr =[
    ["ali", "classroom1"],
    ["john", "classroom1"],
    ["Doe", "classroom1"],
    ["ahmed", "classroom2"],
    ["Mo", "classroom2"],
    ["Wael", "classroom3"]
];

let classrooms = new Map();

for (let item of arr) {
    const [name, classroom] = item;
    if (!classrooms.has(classroom)) {
        classrooms.set(classroom, []);
    }
    classrooms.get(classroom).push(name);
}

console.log(classrooms);
Denis Kotov
  • 857
  • 2
  • 10
  • 29