Function for counting frequency of space separated elements in JavaScript

In this problem statement, our target is to create a function for counting frequency of space separated elements with the help of JavaScript functionalities.

Understanding the Problem

The given problem is stating that we have given a space separated elements and our task is to count the frequency of space separated items. So we will provide some strings with some space separated items and assign a result array to see the counts of the frequency of such items. For example if we have a string with space separated items like "Car Bike Car Bicycle Bike", in this example we can see that Car is appearing 2 times, Bike is appearing 2 times and Bicycle is appearing 1 time so the output should look like {Car: 2, Bike: 2, Bicycle: 1}.

Algorithm

Step 1: Declare a function to count the frequency of the space separated items. Inside this function we will pass a parameter of string as input.

Step 2: Split the given string into an array of elements using the split method with space character as the separator.

Step 3: Create a blank object called freq to keep track of the frequency counts of every item.

Step 4: Traverse over every item in the items array with the help of a for loop.

Step 5: Check that the element already exists as a key in the freq object. If yes, increment its count by 1. If not, add a new key-value pair with the item as key and initial count of 1.

Step 6: Return the freq object as result.

Example

// Function to count the frequency of space separated elements
function countFrequency(str) {
   var elements = str.split(" ");
   var freq = {};
   
   // Traverse the elements of the string
   for (var i = 0; i < elements.length; i++) {
      var element = elements[i];
      
      if (element in freq) {
         freq[element] += 1;
      } else {
         freq[element] = 1;
      }
   }
   
   return freq;
}

var sentence = "apple banana orange banana apple";
var result = countFrequency(sentence);
console.log(result);
{ apple: 2, banana: 2, orange: 1 }

Using Modern JavaScript Approach

Here's a more concise approach using ES6 features:

function countFrequencyModern(str) {
   return str.split(" ").reduce((freq, element) => {
      freq[element] = (freq[element] || 0) + 1;
      return freq;
   }, {});
}

const sentence = "javascript node react javascript node";
const result = countFrequencyModern(sentence);
console.log(result);
{ javascript: 2, node: 2, react: 1 }

Handling Edge Cases

It's important to handle empty strings and extra spaces:

function countFrequencyRobust(str) {
   if (!str || str.trim() === "") {
      return {};
   }
   
   // Filter out empty strings from multiple spaces
   var elements = str.split(" ").filter(element => element !== "");
   var freq = {};
   
   for (var i = 0; i < elements.length; i++) {
      var element = elements[i];
      freq[element] = (freq[element] || 0) + 1;
   }
   
   return freq;
}

var testString = "  hello   world  hello  ";
console.log(countFrequencyRobust(testString));
{ hello: 2, world: 1 }

Time and Space Complexity

Time Complexity: O(n), where n is the length of the input string. The split operation is O(n) and the loop iteration is O(m) where m is the number of elements, which is at most n.

Space Complexity: O(m), where m is the number of unique elements in the string for storing the frequency object.

Conclusion

We have efficiently solved the problem of counting frequency of space separated elements using JavaScript objects. The solution handles edge cases and provides optimal time complexity for processing large input strings.

Updated on: 2026-03-15T23:19:00+05:30

346 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements