Home > OS >  (javascript) How to group data by type
(javascript) How to group data by type

Time:11-16

Here's the data.

[{
    "id": 1,
    "type": "tv",
    "name": "name1"
},
{
    "id": 2,
    "type": "movie",
    "name": "name2"
},
{
    "id": 3,
    "type": "person",
    "name": "name3"
},
{
    "id": 4,
    "type": "tv",
    "name": "name4"
}]

The method I used is below:

Currently my code doesn't create types dynamically. Declare an array and push it.

I want to make the type dynamic, but I don't know how.

Is there a better way?

const movieList = [], tvList = [], personList = [];
arr.forEach(e=>{
   switch (e.type) {
        case 'movie':
          movieList.push(e);
          break;
        case 'tv':
          tvList.push(e);
          break;
       case 'person':
           personList.push(e)
        default:
          break;
      }
});

Thanks for your help

CodePudding user response:

There is Array.prototype.group but it's still experimental and not supported in all environments. So in the meantime, you could use a function similar to it. This one returns an object with the keys given. You can destructure the returned object and rename the keys to get a specific group as well:

const data = [{"id":1,"type":"tv","name":"name1"},{"id":2,"type":"movie","name":"name2"},{"id":3,"type":"person","name":"name3"},{"id":4,"type":"tv","name":"name4"}];

function group(array, getKey) {
    const out = {};
    
    array.forEach((item) => {
        const key = getKey(item);
        
        if (!(key in out)) out[key] = [];
        
        out[key].push(item);
    });
    
    return out;
}

const {
    movie: movieList,
    tv: tvList,
    person: personList,
} = group(data, (item) => item.type);

console.log(movieList);
console.log(tvList);
console.log(personList);

  • Related