Open In App

How to return the singular/plural form of word based on input number in JavaScript ?

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will learn how to return the singular or plural form of the word based on the input number. This can be used in situations where dynamically changing words are required based on the value. This can be achieved using two approaches.

Approach 1: Passing both the singular and plural versions of the word to the function. In this approach, a simple function could be created that takes in the singular and plural versions of the word along with the count value and returns the appropriate word depending on the count. We can use a ternary operator (?) to check the count required.

Syntax:

function pluralizeWord(singularWord, pluralWord, count) {
  return count > 1 ? pluralWord : singularWord;
}

Example 1:

Javascript




function pluralizeWord(singularWord, pluralWord, count) {
  return count > 1 ? pluralWord : singularWord;
}
  
console.log(1, pluralizeWord("geek", "geeks", 1));
console.log(4, pluralizeWord("geek", "geeks", 4));
console.log(4, pluralizeWord("spy", "spies", 4));
console.log(1, pluralizeWord("man", "men", 1));
console.log(4, pluralizeWord("man", "men", 4));


Output:

1 "geek"
4 "geeks"
4 "spies"
1 "man"
4 "men"

Approach 2: Creating a dictionary of all the possible plural versions of the words. The above approach is inefficient if a lot of words are being repeated in the code. We can solve this by creating a dictionary of the plural values of the word and using this dictionary to choose the appropriate word after checking the count.

Syntax:

let pluralDict = {
      "geek": "geeks",
      "spy": "spies",
      "foot": "feet",
      "woman": "women"
    }


function pluralizeWord(singularWord, count) {
  return count > 1 ? pluralDict[singularWord] : singularWord;
}

Example 2:

Javascript




// Define the dictionary with the
// key-value pairs as the singular
// and plural versions of the word
let pluralDict = {
  "geek": "geeks",
  "spy": "spies",
  "foot": "feet",
  "woman": "women"
}
  
function pluralizeWord(singularWord, count) {
  return count > 1 ?
    pluralDict[singularWord] : singularWord;
}
  
console.log(4, pluralizeWord("geek", 4));
console.log(1, pluralizeWord("geek", 1));
console.log(4, pluralizeWord("spy", 4));
console.log(1, pluralizeWord("woman", 1));
console.log(4, pluralizeWord("foot", 4));


Output:

 4 "geeks"
 1 "geek"
 4 "spies"
 1 "woman"
 4 "feet"


Last Updated : 15 Feb, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads