Skip to content

Instantly share code, notes, and snippets.

@Spuffynism
Last active August 24, 2022 06:10
Show Gist options
  • Select an option

  • Save Spuffynism/05998f6fb57e542ccd39d9a0d97ba8a5 to your computer and use it in GitHub Desktop.

Select an option

Save Spuffynism/05998f6fb57e542ccd39d9a0d97ba8a5 to your computer and use it in GitHub Desktop.
Takes a streaming history spotify file and sorts the tracks by listening count
let fs = require('fs');
let path = process.cwd();
console.log('looking for StreamingHistory.json file in ' + path + '\\data\\');
let buffer = {};
try {
buffer = fs.readFileSync(path + "\\data\\StreamingHistory.json");
} catch (e) {
console.log("ERROR: File not found in " + e.path);
return;
}
let tracks = JSON.parse(buffer.toString());
let trackCount = {};
let stringifiedTrack = '';
// associate a count to each track
tracks.forEach((track) => {
delete track.time;
let stringifiedTrack = JSON.stringify(track);
if (!trackCount[stringifiedTrack])
trackCount[stringifiedTrack] = 1;
else
trackCount[stringifiedTrack]++;
});
let tracksWithCount = [];
let trackWithCount = {};
// create track objects with a count property
for (track in trackCount) {
trackWithCount = JSON.parse(track);
trackWithCount.count = trackCount[track];
tracksWithCount.push(trackWithCount);
}
// sort the tracks by count (number of times listened)
tracksWithCount.sort((a, b) => {
return (a.count > b.count) ? -1 : (a.count < b.count) ? 1 : 0;
});
// save the results
let resultsFilePath = path + "\\TracksByListeningCount.json";
fs.writeFile(resultsFilePath, JSON.stringify(tracksWithCount), (err) => {
if (err) {
console.log(err);
}
console.log("The results were saved to " + resultsFilePath);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment