This is a homework problem. I need to write a function called 'allBy' that takes (artist) as an argument.
When run, this function should return an array of all records in "collection" that are by the given artist.
I've written a function that will return only one record, but not multiple.
The console logs are a function that adds a record to the collection.
let collection = [];
function addToCollection( title, artist, year) {
collection.push({title, artist, year}); // adds album to array
return {title, artist, year}; // returns newly created object
} // end of addToCollection function
console.log( addToCollection('The Real Thing', 'Faith No More',
1989));
console.log( addToCollection('Angel Dust', 'Faith No More',
1992));
console.log( addToCollection( 'Nevermind', 'Nirvana', 1991));
console.log( addToCollection( 'Vulgar Display of Power',
'Pantera', 1991));
function allBy(artist) {
for ( let i = 0; i < collection.length; i++) {
// for ( disc of collection) {
if (collection[i].artist === artist) {
return [collection[i].title];
}
}
}
I want to get all records by the given artist in the form of an array, but I'm only able to get one. Am I even close on this?
The main function, allBy()
, returns as soon as it sees the first matching artist. Try declaring an empty array and storing the matches you find in it so you can return the array outside the loop.
function allBy(artist) {
var matches = []; // create an empty array to store our matches
for ( let i = 0; i < collection.length; i++) {
// console.log('current collection item: ', collection[i]); // optional: log or add a breakpoint here to understand what's happening on each iteration
if (collection[i].artist === artist) {
matches.push(collection[i].title); // add a match we've found
// return [collection[i].title];
}
}
return matches; // tada!
}
You can just use map
with filter
:
function allBy(artist) {
return collection.filter(({ artist: a }) => a == artist).map(({ title }) => title);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.