regroup values of an array into a new array

Asked

Viewed 66 times

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 get the key Season and group in a new array like this:

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

as I take the values of an api, so there is no way I can define "if Season == 1", I have to take these settings dynamically.

https://jsfiddle.net/xkqy8xqo/

2 answers

3


Well I’m not really sure, but, by the layout done is wrong, because inside each element created if it has an array of objects, then the layout would be more or less like this:

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

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

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

  • 1

    thanks for the note, I’ve edited the question.

0

Follow an alternative using only one for and the object for the Asons. No for creates each of the keys for the Asons if they don’t exist and then adds each episode to the Ason episode array.

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 one more attribute duration to make it more evident that it meets the needs it has indicated to keep any other information from the episode.

  • only one doubt, the Foot that ta ai is just an example, but it has more values in there, in your example it pushes only 1 value

  • @Leandro What you’re saying is that the object has more things than episode is this ? Can you give a more concrete example?

  • look at this example: http://bit.ly/2DPmpwS

  • @Leandro Certo, I have already edited the answer to contemplate the rest of the properties that the object may have

Browser other questions tagged

You are not signed in. Login or sign up in order to post.