Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

How to efficiently find the most frequent element of an array, in JavaScript?

/*
  This code demonstrates how to efficiently find the most 
  frequent element of an array.  
  Let n be the size of the array.

  Time complexity: O(n)
  Space complexity: O(n)
*/
function computeElementsFrequencies(arr, map) {
  // Computer the number of occurrences of each
  // array element.
  for (const element of arr) {
    if (map.has(element)) {
      map.set(element, map.get(element) + 1);
    } else {
      map.set(element, 1);
    }
  }
}

function findMostFrequentElements(map) {
  const maxFrequency = Math.max.apply(null, Array.from(map.values()));
  // Return an array containing the most frequent elements
  return Array.from(map.keys()).filter((key) => {
    return map.get(key) === maxFrequency;
  });
}

const map = new Map();
computeElementsFrequencies(
  ["Wissam", "Wissam", "Chadi", "Chadi", "Fawzi"],
  map
);
const mostFrequentElements = findMostFrequentElements(map);
console.log(mostFrequentElements); // [ 'Wissam', 'Chadi' ]
Comment

javascript most frequent in a list

function findMostFrequent(arr) {
	var repsCount = {};
	for (i = 0; i < arr.length; i++) {
		if (!repsCount[arr[i]]) {
			repsCount[arr[i]] = 1;
		} else {
			repsCount[arr[i]] = repsCount[arr[i]] + 1;
		}
	}
	var occursMore = [];
	for (var key in repsCount) {
		if (repsCount[key] > occursMore) {
			occursMore.push(key);
		}
	}
	return occursMore;
}
Comment

PREVIOUS NEXT
Code Example
Javascript :: forever loop in js 
Javascript :: js modulo not working 
Javascript :: javascript Iterate Through Iterables 
Javascript :: body onload jQuery | jQuery equivalent of body onLoad 
Javascript :: random between min and max 
Javascript :: save byte as json string javascript 
Javascript :: call vue function at element load 
Javascript :: automated counter with react hooks 
Javascript :: javascript modify href attr 
Javascript :: core.js:5592 WARNING: sanitizing unsafe URL value 
Javascript :: jquery select element inside element 
Javascript :: js two array combining with id neasted 
Javascript :: textarea events react testing library 
Javascript :: check if class is clicked javascript 
Javascript :: clear ckeditor textarea jquery 
Javascript :: ~~ in javascript 
Javascript :: how to use crypto module in nodejs 
Javascript :: javascript get user from api 
Javascript :: jquery get multiple selected option value 
Javascript :: transition css with js 
Javascript :: python restapi use post json 
Javascript :: json remove &#34 
Javascript :: how to global a variable in javascript 
Javascript :: create auto increment mongodb mongoose 
Javascript :: javascript .target 
Javascript :: When JavaScript was invented month?* 
Javascript :: discord js check if message author is admin 
Javascript :: odd and even in javascript 
Javascript :: window width onload jquery 
Javascript :: app script append two list 
ADD CONTENT
Topic
Content
Source link
Name
2+6 =