我有一个JSON文件,其中有超过2万个条目,并且在Spotify上具有不同轨道的名称。我试图计算特定歌手播放每首歌曲的次数。
NavigationView {
VStack {
...
}.frame(maxHeight:.infinity, alignment: .top)
.padding()
.border(Color.red).navigationBarTitle("", displayMode: .inline)
}
这是我目前的代码。基本上,它的工作是循环遍历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)
数组,并按NF(特别是轨道名称)获取所有包含重复项的条目,然后再次执行此操作,但是这次仅捕获唯一的名称。然后,我在曲目的所有唯一名称上运行dta
,它将获取播放次数并将其推送到countInArray
数组中。
不是特别复杂,它确实可以工作。我想知道是否有更好,更短的方法。
答案 0 :(得分:0)
我认为您应该尝试filter
方法。例如:
function countInArray(array, what) {
const foundItems = array.filter(value => value === what);
nfPlays.push(foundItems.length)
return foundItems.length;
}
或
const foundTracks = dta.filter(track => track.artistName === "NF");
答案 1 :(得分:0)
您可以使用比数组(indexOf)呈现更快查询的Map
const dta = [
{ trackName:'a', artistName:'NF' },
{ trackName:'a', artistName:'NF' },
{ trackName:'b', artistName:'NF' },
{ trackName:'b', artistName:'other' },
]
const trackNameToCount = dta.reduce((m, track) => {
if (track.artistName === 'NF') {
const n = m.get(track.trackName) || 0
m.set(track.trackName, n+1)
}
return m
}, new Map())
;[...trackNameToCount.entries()].forEach(([name, count]) => {
console.log(`${name} played ${count} times`)
})
答案 2 :(得分:0)
希望我了解您在做什么。我建议使用对象类型来处理重复项。像这样吗?
dta = [
{trackName: "dog", artistName: "NF"},
{trackName: "dog", artistName: "mack"},
{trackName: "dog", artistName: "NF"},
{trackName: "cat", artistName: "fred"},
{trackName: "mouse", artistName: "NF"},
]
nfsongs = {}
dta.forEach(item => {
if (item.artistName==="NF") {
if (item.trackName in nfsongs) {
nfsongs[item.trackName]++;
} else {
nfsongs[item.trackName]=1;
}
}
})
for (key in nfsongs) {
console.log(`${key} has ${nfsongs[key]} plays`)
}