I have an array of objects that contains blogs inside
const blogs = [
{
_id: '5a422a851b54a676234d17f7',
title: 'React patterns',
author: 'Michael Chan',
url: 'https://reactpatterns.com/',
likes: 7,
__v: 0
}, {
_id: '5a422aa71b54a676234d17f8',
title: 'Go To Statement Considered Harmful',
author: 'Edsger W. Dijkstra',
url: 'http://www.u.arizona.edu/~rubinson/copyright_violations/Go_To_Considered_Harmful.html',
likes: 5,
__v: 0
},
{
_id: '5a422b3a1b54a676234d17f9',
title: 'Canonical string reduction',
author: 'Edsger W. Dijkstra',
url: 'http://www.cs.utexas.edu/~EWD/transcriptions/EWD08xx/EWD808.html',
likes: 12,
__v: 0
},
{
_id: '5a422b891b54a676234d17fa',
title: 'First class tests',
author: 'Robert C. Martin',
url: 'http://blog.cleancoder.com/uncle-bob/2017/05/05/TestDefinitions.htmll',
likes: 10,
__v: 0
},
{
_id: '5a422ba71b54a676234d17fb',
title: 'TDD harms architecture',
author: 'Robert C. Martin',
url: 'http://blog.cleancoder.com/uncle-bob/2017/03/03/TDD-Harms-Architecture.html',
likes: 0,
__v: 0
},
{
_id: '5a422bc61b54a676234d17fc',
title: 'Type wars',
author: 'Robert C. Martin',
url: 'http://blog.cleancoder.com/uncle-bob/2016/05/01/TypeWars.html',
likes: 12,
__v: 0
}
];
What I want to do is return the first match of the highest number of likes, even so they are repeated much later, for example in my array of objects those likes: 12
in index 2 and 5 are repeated, so the only thing I want to return is the first match that is the object at index 2 of the array. All the information of that object.
I tried to do it with a reduce but it returns the last match, but not the first.
non-functional code
const favoriteBlog = (blogs) => {
const getFavoriteBlog = (previousValue, currentValue) => {
return previousValue.likes > currentValue.likes ? previousValue: currentValue;
};
return blogs.reduce(getFavoriteBlog);
};
An idea occurs to me, you order the blogs from highest to lowest likes. There you already know that the one that is in position
0
is going to be the post that has the most likes or one of the ones that has the most likes. Then you only find out how many likes that post has and you only use the methodfind
, which returns the first match.EDITED ANSWER ----- It occurs to me to make a map to the array, to make it faster.
To do what you request you can go through the array with a normal for or with a for in, inside the for you get the maximum value of blog likes and store it in a variable, as in your blogs you have two that the number of likes are 12 will only store a 12 in that variable. Then you make the direct return of a blog find that you receive as a parameter so that it returns the first object with which it finds a match, which would be the first blog whose likes are 12, if the first blog reaches 12 it will return said first blog.