I have an array with objects that include the keys; title, authors and rating. I want to search for the first object where the title value starts with the letter 'A'
const books = [{
title: 'Good Omens',
authors: ['Terry Pratchett', 'Neil Gainman'],
rating: 4.25
},
{
title: 'Bone: The Complete Edition',
authors: ['Jeff Smithh'],
rating: 4.42
},
{
title: 'American Gods',
authors: ['Neil Gainman'],
rating: 4.11
},
{
title: 'A Gentleman in Moscow',
authors: ['Amor Towles'],
rating: 4.36
}
]
const titleA = books.find(y => y.indexOf('A') === 0);
And I get this error:
TypeError: y.indexOf is not a function
Your code is partially fine except for these details:
The indexOf method does not seem to be the best option to filter by matching a character at the beginning or end of a string, I recommend documenting its use in detail here
For the previous point, a regular expression looks like the best option, where we will look for the character
A
to be present at the beginning of the string with^[caracter]
On the other hand, although you have an array, it is made up of N objects inside, given that you have to do the syntax of:
book.propiedad
which for this example would bebook.title
where we will extract the values from to search for the existence of the patternWith a conditional you evaluate if the regex is fulfilled and consequently you return to the object that shows all the data of the book
Code:
Just as an extra we can reduce it to one line by substituting our regular if for the use of a ternary conditional:
test