Find Mode of an Array using JavaScript
Last Updated :
18 Mar, 2024
To find the mode in an array with JavaScript, where the mode is the number occurring most frequently. Various approaches can be employed to find the mode, and an array may have multiple modes if multiple numbers occur with the same highest frequency.
Example:
Input:
3, 6, 4, 6, 3, 6, 6, 7 , 6, 3 , 3
Output:
6 , 3
Use the below approaches to Find Mode in an Array using JavaScript
Finding Mode in an Array using a Frequency Map
In this approach, We initialize an empty object as a frequency map to track each element's count. By iterating through the array, we update the frequency map accordingly. Then, we determine the mode by finding the element with the highest frequency in the frequency map. Finally, we return this element as the mode of the array.
Example: Implementation of Finding Mode in an Array in JavaScript using a Frequency Map
JavaScript
function findModes(arr) {
// Create a frequency map
const frequencyMap = {};
arr.forEach(number => {
frequencyMap[number] =
(frequencyMap[number] || 0) + 1;
});
let modes = [];
let maxFrequency = 0;
for (const number in frequencyMap) {
const frequency = frequencyMap[number];
if (frequency > maxFrequency) {
maxFrequency = frequency;
modes = [parseInt(number)];
} else if (frequency === maxFrequency) {
modes.push(parseInt(number));
}
}
return modes;
}
const input = [5, 4, 5, 6, 6, 6, 7, 5];
const result = findModes(input);
console.log(result);
Time Complexity : O(n)
Space Complexity : O(n)
Finding Mode in an Array using an object
To find mode in an array we will create an object to find mode in an array using JavaScript. Then we will traverse through the array and count the frequency of each element. Now we will find which element has the maximum frequency. We will return the element having maximum frequency. If more than one element exists we will return all the elements.
Example: Implementation of Finding Mode in an Array in JavaScript using an object
JavaScript
function mode(input) {
// Object to store the frequency of each element
let mode = {};
// Variable to store the frequency of the current mode
let maxCount = 0;
// Array to store the modes
let modes = [];
// Iterate through each element of the input array
input.forEach(function (e) {
if (mode[e] == null) {
mode[e] = 1;
} else {
mode[e]++;
}
if (mode[e] > maxCount) {
// Update the current mode and its frequency
modes = [e];
maxCount = mode[e];
} else if (mode[e] === maxCount) {
modes.push(e);
}
});
return modes;
}
let input = [1, 2, 3, 3, 3, 2, 2];
console.log(mode(input));
Time Complexity : O(n)
Space Complexity : O(n)
Finding Mode in an Array using Sorting
This approach involves sorting the array, and then iterating through it to count each element's occurrences. We update the mode whenever we encounter a new maximum count. Finally, we return the mode element.
Example: Implementation of Finding Mode in an Array in JavaScript using sorting.
JavaScript
function Mode(arr) {
// Sort the array in ascending order
arr.sort((a, b) => a - b);
let modes = [];
let maxCount = 0;
let currentCount = 1;
let i = 0;
while (i < arr.length) {
// Count the occurrences of the current element
while (i < arr.length - 1 &&
arr[i] === arr[i + 1]) {
currentCount++;
i++;
}
// Update the modes array if needed
if (currentCount === maxCount) {
modes.push(arr[i]);
} else if (currentCount > maxCount) {
maxCount = currentCount;
modes = [arr[i]];
}
// Reset currentCount for the next element
currentCount = 1;
i++;
}
return modes;
}
const input = [1, 2, 3, 3, 3, 2, 2];
const modes = Mode(input);
console.log(modes);
Time Complexity : O(nlogn)
Space Complexity : O(logn)
Similar Reads
Find the min/max element of an Array using JavaScript
To find the minimum or maximum element in a JavaScript array, use Math.min or Math.max with the spread operator.JavaScript offers several methods to achieve this, each with its advantages.Using Math.min() and Math.max() Methods The Math object's Math.min() and Math.max() methods are static methods t
2 min read
JavaScript Array find() Method
The find() method in JavaScript looks through an array and returns the first item that meets a specific condition you provide. If no item matches, it returns undefined. It skips any empty space in the array and doesnât alter the original array.Syntax:array.find(function(currentValue, index, arr), th
3 min read
Find the OR and AND of Array elements using JavaScript
Given an array and the is task to find the OR and AND operations of the values of an Array using JavaScript. These are the following methods: Using simple for loopUsing reduce() MethodApproach 1: Using simple for loop It uses a simple method to access the array elements by an index number and use th
2 min read
JavaScript Array Search And Remove String.
Arrays are widely used to store and manipulate collections of data. Sometimes we may need to search for a specific string within an array and remove it. This operation can be useful in various cases, such as filtering out unwanted items, managing user inputs, or processing data from an external sour
2 min read
JavaScript â Min Element in an Array
These are the following ways to find the minimum element in JS array:Note: You must add a conditional check for checking whether the given array is empty or not, if the array is not empty then you can use the given below approaches to find out the minimum element among them.1. Using Math.min() Metho
3 min read
Types of Arrays in JavaScript
A JavaScript array is a collection of multiple values at different memory blocks but with the same name. The values stored in an array can be accessed by specifying the indexes inside the square brackets starting from 0 and going to the array length - 1([0]...[n-1]). A JavaScript array can be classi
3 min read
JavaScript - Find Index of a Value in Array
Here are some effective methods to find the array index with a value in JavaScript.Using indexOf() - Most Used indexOf() returns the first index of a specified value in an array, or -1 if the value is not found. JavaScriptconst a = [10, 20, 30, 40, 50]; // Find index of value 30 const index = a.inde
2 min read
JavaScript Array findLast() Method
The JavaScript findLast() method is used to retrieve the last element in an array that meets a specified condition.Example 1: This example shows how findLast() can be used to find the last even number in an array.JavaScriptconst a = [1, 3, 5, 7, 6, 8]; const b = a.findLast(num => num % 2 === 0);
2 min read
JavaScript indexOf() method in an Object Array
In JavaScript, indexOf() methods provide the first index at which the given element exists, and -1 in case it is not present in the array. Syntax: indexOf(element)indexOf(element, start);Parameters: element: the element to be searched in the input arraystart: the index from which the search has to b
2 min read
JavaScript Int8Array of() Method
The Int8Array constructor represents an array of two's-complement of 8-bit signed integers. By default, the contents of Int8Array are initialized to 0. The Int8Array.of() method is used to create a new Int8Array from an array-like or iterable object. Syntax: Int8Array.of(el0, el1, ...) Parameter: Th
2 min read