Skip to main content

Find the frequency of each element in an array in node js

Js program for Find the frequency of each element in an array. Here problem description and explanation.

class Occurrence
{
	// Function which is display array elements
	display(arr)
	{
		for (var i = 0; i < arr.length; ++i)
		{
			process.stdout.write("  " + arr[i]);
		}
		process.stdout.write("\n");
	}
	// Count occurrence of given array
	frequency(arr)
	{
		// Display given array
		this.display(arr);
		// Create a empty map
		var map = new Map();
		for (var i = 0; i < arr.length; i++)
		{
			if (map.has(arr[i]))
			{
				// When key exists then update value
				map.set(arr[i], map.get(arr[i]) + 1);
			}
			else
			{
				// Add new element
				map.set(arr[i], 1);
			}
		}
		console.log("  Occurrence ");
		//  Display calculated result
		for (let [key, value] of map)
		{
			console.log("  " + key + "  :  " + map.get(key));
		}
	}
}

function main()
{
	// Array element
	var arr = [1, 3, 2, 1, 4, 2, 7, 9, 1, 3, 3, 4, 7];
  	var task = new Occurrence();
	task.frequency(arr);
}
// Start program execution
main();

Output

  1  3  2  1  4  2  7  9  1  3  3  4  7
  Occurrence
  1  :  3
  3  :  3
  2  :  2
  4  :  2
  7  :  2
  9  :  1




Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment