Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Displaying likes on a post wherein array specifies the names of people that liked a particular post using JavaScript
We need to write a JavaScript function that takes an array of names representing people who liked a post. The function should format the output based on the number of likes: show all names for 3 or fewer likes, or show the first two names plus the remaining count for more than 3 likes.
Problem Statement
Create a function that displays likes in a user-friendly format:
- 0 likes: "no one likes this"
- 1 like: "John likes this"
- 2 likes: "John and Mary like this"
- 3 likes: "John, Mary and Bob like this"
- 4+ likes: "John, Mary and X others like this"
Solution
Here's an elegant solution using an array with calculated indices:
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));
console.log(displayLikes(['Alice']));
console.log(displayLikes(['Alice', 'Bob']));
console.log(displayLikes([]));
Ram, Manohar and 3 others like this Alice likes this Alice and Bob like this no one likes this
How It Works
The function uses a clever array indexing approach:
- Creates an array of 5 template strings for different like counts
- Uses
Math.min(4, names.length)to get the correct index (capped at 4) - Returns the appropriate template string with names interpolated
Alternative Approach
Here's a more readable conditional approach:
const displayLikesConditional = (names) => {
const count = names.length;
if (count === 0) return 'no one likes this';
if (count === 1) return `${names[0]} likes this`;
if (count === 2) return `${names[0]} and ${names[1]} like this`;
if (count === 3) return `${names[0]}, ${names[1]} and ${names[2]} like this`;
return `${names[0]}, ${names[1]} and ${count - 2} others like this`;
};
const testNames = ['John', 'Mary', 'Bob', 'Alice', 'Charlie'];
console.log(displayLikesConditional(testNames));
John, Mary and 3 others like this
Comparison
| Approach | Lines of Code | Readability | Performance |
|---|---|---|---|
| Array Indexing | Shorter | Clever but less obvious | Slightly faster |
| Conditional | Longer | More explicit | Standard |
Conclusion
Both approaches work well for displaying post likes. The array indexing method is more concise, while the conditional approach is more readable and maintainable for beginners.
Advertisements
