James Paul Molnar
James Paul Molnar

Reputation: 17

return not giving expected answer

I'm writing a function that loops through an array of objects and trying to return the index of a particular object.

My instinct was to loop through the array and find the matching property value. But this only gives me the index of the property within the object, which is always 0.

The first function addToCollection adds a record to a record collection with title, artist, and year as arguments. I want my new function to find a particular album and return its index within the collection array.

 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 findRecord ( title ) {    //function not working!!
   for (let i = 0; i < collection.length; i++) {
     if (collection[i].title === title) {
       return collection[i].title.indexOf(title);
     } else {
       return false;
     }
   }
 }

What I want is to get the index of the object within the array. I just keep getting 0.

Upvotes: 1

Views: 37

Answers (1)

Hayk Aghabekyan
Hayk Aghabekyan

Reputation: 1087

return collection[i].title.indexOf(title);

what is the code above? :)

return i;

and you will get the index

Upvotes: 1

Related Questions