Find the frequency of each element in an array in typescript
Ts program for Find the frequency of each element in an array. Here more information.
class Occurrence
{
// Function which is display array elements
public static display(arr: number[])
{
console.log(" ",arr);
}
// Count occurrence of given array
public static frequency(arr: number[])
{
// Display given array
Occurrence.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 (const [key,value] of map)
{
console.log(" " + key + " : " + value);
}
}
public static main(args: string[])
{
// Array element
var arr: number[] = [1, 3, 2, 1, 4, 2, 7, 9, 1, 3, 3, 4, 7];
Occurrence.frequency(arr);
}
}
Occurrence.main([]);
/*
file : code.ts
tsc --target es6 code.ts
node code.js
*/
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
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