Displaying likes on a post wherein array specifies the names of people that liked a particular post using JavaScript


Problem

We are required to write a JavaScript function that takes in an array of names (string). This array specifies the names of people that liked a particular post on some social networking site.

If the count of likes are less than or equal to three our function should simply return all names saying these people liked the post but if the count is greater than three then our function should return first two names and remaining count.

Example

Following is the code −

 Live Demo

const names = ['Ram', 'Manohar', 'Jay', 'Kumar', 'Vishal'];
const displayLikes = (names) => {
   return [
      'no one likes this',
      `${names[0]} likes this`,
      `${names[0]} and ${names[1]} like this`,
      `${names[0]}, ${names[1]} and ${names[2]} like this`,
      `${names[0]}, ${names[1]} and ${names.length - 2} others like this`,
   ][
      Math.min(4, names.length)
   ];
};
console.log(displayLikes(names));

Output

Ram, Manohar and 3 others like this

Updated on: 17-Apr-2021

211 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements