Below I am trying to pull songs from SoundCloud (based on an array of genres that I pass through), put these songs into an array, return that array, and then flatten that array (since the returned array is an array of arrays).
var genreArray = ['pop', 'hip-hop', 'alternative'];
var each = function (collection, callback) {
if (Array.isArray(collection)) {
for (var i=0; i<collection.length; i++) {
callback(collection[i]);
}
} else {
for (var key in collection) {
callback(collection[key]);
}
}
};
var flatten = function (array) {
var results = [];
each (array, function(item) {
if(Array.isArray(item)) {
results = results.concat(flatten(item));
} else {
results.push(item);
}
})
return results;
};
var getSongs = function (genreSelection) {
var mySongArray = [];
each (genreSelection, function (genre) {
SC.get('/tracks', { tags: genre }).then(function(tracks) {
mySongArray.push(tracks);
});
});
return mySongArray;
};
When I include the following, mySongs
correctly returns the array of arrays that it should, but myFlattenedSongs
returns an empty array. It's weird because when I take the line with myFlattened
songs out of my code and then go into the console and manually put it in, it flattens the array of arrays as it should. Any thoughts on what might be going wrong here?
var mySongs = getSongs(genreArray);
var myFlattenedSongs = flatten(mySongs);