Skip to content

Instantly share code, notes, and snippets.

@JoaoCnh
Last active October 14, 2018 09:27
Show Gist options
  • Save JoaoCnh/8cc6e89429f39fd7511cbc6ba04139fc to your computer and use it in GitHub Desktop.
Save JoaoCnh/8cc6e89429f39fd7511cbc6ba04139fc to your computer and use it in GitHub Desktop.
Reduce object from array
var obj = songs.reduce(function (acc, currValue) {
var artist = currValue.artist;
var artistCount = acc[artist] ? acc[artist] + 1 : 1;
var newObj = {};
newObj[artist] = artistCount;
return Object.assign(acc, newObj);
}, {});
// ES6
const obj = songs.reduce((acc, currvalue) => {
const artist = currValue.artist;
const artistCount = acc[artist] ? acc[artist] + 1 : 1;
return {
...acc,
[artist]: artistCount,
};
}, {});
console.log(obj); // {Mastodon: 2, Gojira: 2}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment