I'm trying to extract an album list from an iTunes playlist export.
The file has a list of all songs in each album, and I want just 1 entry per album, discarding the song titles.
So, I need to filter on unique album titles.
I can accomplish this iteratively, but was wondering if there's a more elegant way to achieve this through higher-order functions?
Here's the 2D songs array:
var songs[[String]]
Here's the structure of inner array:
artist, album, song, ...
Array example:
("Beck", "Odelay", "Odelay")
("Beck", "Odelay", "Hotwax")
("Beck", "Odelay", "Derelict")
...
After processing, there should be just a single entry for "Odelay":
("Beck", "Odelay", "Odelay")
In SQL database it's trivial to accomplish this query:
SELECT artist, DISTINCT album FROM songs ORDER BY album
Here's my iterative code that achieves my goal:
var songs = [[""]]
var uniqueAlbums = [[""]]
<code to load songs array here>
// grab list of unique album titles
let albumTitles = (Set(songs.map { $0[2] })).sorted()
var cnt = 0
for title in albumTitles {
// grab all songs for this album
let currentAlbum = songs.filter { $0[2] == title }
// loop thru songs till last song, then add only one entry per album to new array
for album in currentAlbum {
if cnt < currentAlbum.count - 1 {
cnt += 1
} else {
uniqueAlbums.append(album)
}
}
cnt = 0
}
// uniqueAlbums[] is now a filtered collection of songs[] with only 1 album per line
It'd be neat if you could use SQL-like queries within Swift for 2D arrays.