List Format
JavaScript
medium
25 mins
Write a function that takes an array of strings and returns a human-readable list formatted with commas and the word "and" before the last item. This is similar to how natural language lists are formatted in English.
For example:
["apple"]→"apple"["apple", "banana"]→"apple and banana"["apple", "banana", "cherry"]→"apple, banana and cherry"["", "two", ""]→", two and "
Example Inputs & Outputs
formatList([]) // → "" formatList(["apple"]) // → "apple" formatList(["apple", "banana"]) // → "apple and banana" formatList(["apple", "banana", "cherry"]) // → "apple, banana and cherry" formatList(["one", "two", "three", "four"]) // → "one, two, three and four"
Constraints & Edge Cases
- The input will always be an array of strings
- Return an empty string if the array is empty
- Handle 1-item, 2-item, and 3+ item cases correctly
- Items may include empty strings, but treat them as valid values
Companies:
twitter
linkedin
oyo
Solve Similar questions 🔥
Want to upskill? Explore our courses!
Namaste DSA
Master DSA from scratch with numerous problems, and expert guidance.
Namaste React
Wanna dive deep into React and become Frontend Expert? Learn with me now!
Namaste Frontend System Design
The most comprehensive and detailed course for frontend system design.
Namaste Node.js
Wanna dive deep into Node.js? Enroll into `Namaste Node.js` now!
