Sling Academy
Home/JavaScript/JavaScript: Find the mode of an array (the most common element)

JavaScript: Find the mode of an array (the most common element)

Last updated: March 17, 2023

Introduction

The mode of an array is the most frequently occurring element in the array. It is one of the measures of central tendency, along with the mean and median. The mode can be used to describe the typical value or the most common preference in a data set.

It is possible that there is more than one mode in a given array (if two or more elements have the same frequency). For example, in the array [1, 2, 3, 3, 4, 4], both 3 and 4 are modes because they appear twice each.

This practical, example-based article will walk you through a couple of different ways to identify the mode of a given array in modern JavaScript.

Using the reduce() method

We will use a reduce() method to create an object that stores the frequency of each element in the array and then use the Object.entries() and sort() methods to find the element(s) with the highest frequency. The example below will clearly depict what I mean:

// an array of words
let arr = [
  'sling',
  'academy',
  'blue',
  'dog',
  'sling',
  'red',
  'forest',
  'sling',
  'blue',
  'red',
];

// Create an object that stores frequencies using reduce()
let obj = arr.reduce((acc, cur) => {
  // Increment current value or set it to one if not found
  acc[cur] = (acc[cur] || 0) + 1;

  // Return updated accumulator object
  return acc;
}, {}); // Initialize accumulator object as empty

// Convert object into an array of key-value pairs
let entries = Object.entries(obj);

// Sort entries by descending order of values (frequencies)
entries.sort((a, b) => b[1] - a[1]);

// Get max frequency from first entry
let maxFreq = entries[0][1];

// Filter entries by matching values with max frequency and map them to keys (elements)
let modes = entries
  .filter(([key, value]) => value === maxFreq)
  .map(([key]) => key);

console.log(modes);

Output:

['sling']

We store the result in an array in case there are multiple modes.

Using a Map object

The alternative solution is to use a Map object to store the frequency of each element in the array and then loop through the map to find the element(s) with the highest frequency.

Example:

// Given an array of words arr
let arr = ['apple', 'banana', 'orange', 'apple', 'pear', 'banana'];

// Create an empty map
let map = new Map();

// Initialize max frequency to zero
let maxFreq = 0;

// Initialize modes to empty array
let modes = [];

// Loop through each word in arr
for (let word of arr) {
  // Get current frequency of word or zero if not found
  let freq = map.get(word) || 0;

  // Increment frequency by one
  freq++;

  // Set updated frequency of word in map
  map.set(word, freq);

  // If current frequency is greater than max frequency
  if (freq > maxFreq) {
    // Update max frequency
    maxFreq = freq;

    // Reset modes to only word
    modes = [word];

    // If current frequency is equal to max frequency
  } else if (freq === maxFreq) {
    // Add word to modes array
    modes.push(word);
  }
}
console.log(modes);

Output:

["apple" ,"banana"]

Using Lodash (One-Line Solution)

This solution is very short since it solves the task with only a single line of code. However, it involves a third-party library named lodash, and its readability is not much. Another drawback is that this approach only returns one mode even if there are multiple modes in the array.

Install lodash:

npm i lodash

Or use it through CDN with the script tag:

<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js">

Example usage:

const arr = [1, 2, 3, 4, 2, 3, -1, 0, 2, 2]

let mode = _.chain(arr).countBy().entries().maxBy(_.last).thru(_.head).value();

console.log(mode);

Output:

2

That’s it. The tutorial ends here. Happy coding & have a nice day!

Next Article: How to effectively use the filter() method in Javascript

Previous Article: JavaScript: Finding the Mean (Average) of an Array

Series: Working with Arrays in JavaScript

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration