regroup values from an array into a new array

1

I have an array of values like this: [{season:1, episode:1},{season:1, episode:2},{season:2, episode:1},{season:2, episode:2}]

What I want to do is take the key season and group it in a new array like this:

{"season 1":[{episode:1},{episode:2}], "season 2":[{episode:1},{episode:2}]}

As I get the values from an api, then there's no way I can define "if season == 1", I have to get those seasons dynamically.

link

    
asked by anonymous 30.01.2018 / 18:11

2 answers

3

Well I'm not sure, but because the layout is wrong, because within each element you create if you have an array of objects, then the layout would look something like this:

{
  "season 1": [
    {
      "episode": 1
    },
    {
      "episode": 2
    }
  ],
  "season 2": [
    {
      "episode": 1
    },
    {
      "episode": 2
    }
  ]
}

Then, to create a new key layout and value it was used as a reference Group By in Javascript as a basis and with some modifications if you have the answer above:

var items = [{
  season: 1,
  episode: 1
}, {
  season: 1,
  episode: 2
}, {
  season: 2,
  episode: 1
}, {
  season: 2,
  episode: 2
}];

Array.prototype.groupBy = function() {
  return this.reduce(function(groups, item) {
    var keys = Object.keys(item);
    var val = keys[0] + ' ' + item['season'];
    groups[val] = groups[val] || [];
    var obj = {
      get [keys[1]]() {
        return item[keys[1]];
      }
    }
    groups[val].push(obj);
    return groups;
  }, {});
}

var news = items.groupBy();

console.log(news);

Simple

var items = [{
  season: 1,
  episode: 1
}, {
  season: 1,
  episode: 2
}, {
  season: 2,
  episode: 1
}, {
  season: 2,
  episode: 2
}];

let groups = {};

for(let item in items)
{
  var name = 'season' + ' ' + items[item]['season'];
  if (groups[name] === undefined)
      groups[name] = [];
  var add = items[item];
  delete add['season'];
  groups[name].push(add);
}

console.log(groups);
    
30.01.2018 / 19:13
0

Here is an alternative using only for and the object for the seasons. No for will create each of the keys for the seasons if they do not exist and then add each episode to the season's array of episodes.

var episodes = [{
  season: 1,
  episode: 1,
  duration:53
}, {
  season: 1,
  episode: 2,
  duration:126
}, {
  season: 2,
  episode: 1,
  duration:119
}, {
  season: 2,
  episode: 2,
  duration:188
}];

let seasons = {};
episodes.forEach(e => {
  let key = 'season ${e.season}'; //criar a chave de cada objeto
  if (!(key in seasons)){ //se ainda não existe cria o array de episódios
    seasons[key] = []; 
  }
  delete e["season"]; //remover a season na informação do episodio
  seasons[key].push(e); //adiciona todas as informações do episodio ao array
});

console.log(seasons);

I put another duration attribute to make it more evident that it responds to the needs you indicated to keep any other episode information.

    
30.01.2018 / 19:37