I have a JSON file with over 20k entries with the names of different tracks on Spotify. I was trying to count the number of times each song has been played by a specific artist.
function countInArray(array, what) {
var count = 0;
for (var i = 0; i < array.length; i++) {
if (array[i] === what) {
count++;
}
}
nfPlays.push(count)
return count;
}
nfSongs2 = []
nfSongs = []
nfPlays = []
for(var i = 0; i < dta.length; i++) {
if(dta[i].artistName === "NF") {
nfSongs.push(dta[i].trackName)
}
}
for(var i = 0; i < dta.length; i++) {
if(nfSongs2.indexOf(dta[i].trackName) === -1 && dta[i].artistName === "NF") {
nfSongs2.push(dta[i].trackName)
}
}
for(var i = 0; i < nfSongs2.length; i++) {
console.log(`${nfSongs2[i]} has ${countInArray(nfSongs, nfSongs2[i])} plays`)
}
console.log(countInArray(nfSongs, "WHY"))
console.log(nfPlays)
console.log(nfSongs2)
console.log(nfSongs)
That's currently my code. Basically what it does is loop through the dta
array and grab all the entries by NF (specifically the track names) which includes the duplicates, and then it does that again but this time, only grabbing unique names. Then I run countInArray
on all the unique names of the tracks which will grab the number of plays and push it to the nfPlays
array.
Not especially complicated and it does work. I was wondering if there is a better, shorter way of doing this.