Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
Sort an array of objects using Boolean property in JavaScript
Next article icon

Sorting Array of Number by Increasing Frequency using JavaScript

Last Updated : 17 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

To sort an array of given numbers based on the frequency of occurrence of each number first sort the array such that the elements repeated for the least number of times appear first followed by the elements with increasing frequency.

Example:

Input:
array = [3, 3, 1, 1, 1, 8, 3, 6, 8, 8]

Output:
[6, 1, 1, 1, 3, 3, 3, 8, 8, 8]

Explanation:
Number 6 occurs 1 time
Number 1 occurs 3 times
Number 3 occurs 3 times
Number 8 occurs 3 times

Below are the approaches to sort an array of Numbers by increasing frequency using JavaScript:

Table of Content

  • Using an Object
  • Using Map

Using an Object

Initialize an empty object to store the frequency of each number. Iterate through the array and count the frequency of each number. Sort the array based on increasing frequency using a custom comparator function. If two numbers have different frequencies, sort them based on their frequencies in ascending order. If two numbers have the same frequency, sort them based on their values in ascending order. Return the sorted array.

Example: Demonstration of Sorting array of Numbers by increasing frequency in JavaScript using an Object.

JavaScript
function sortIncreasFreq(arr) {     const freqMap = {};     arr.forEach(num => {         freqMap[num] =                  (freqMap[num] || 0) + 1;     });      return arr.sort((a, b) => {         if (freqMap[a] !== freqMap[b]) {             return freqMap[a] - freqMap[b];         } else {             return a - b;         }     }); }  const arr = [3, 3, 1, 1, 1, 8, 3, 6, 8, 8]; console.log("Sorted by increasing frequency:",                      sortIncreasFreq(arr)); 

Output
Sorted by increasing frequency: [   6, 1, 1, 1, 3,   3, 3, 8, 8, 8 ] 

Time Complexity: O(n log n)

Space Complexity: O(n)

Using Map

Initialize an empty Map to store the frequency of each number. Iterate through the array and update the frequency of each number. Sort the array based on increasing frequency using a custom comparator function. If two numbers have different frequencies, sort them based on their frequencies in ascending order. If two numbers have the same frequency, sort them based on their values in ascending order. Return the sorted array.

Example: Demonstration of Sorting array of Numbers by increasing frequency in JavaScript using Map.

JavaScript
function sortInFreq(arr) {     const freqMap = new Map();     arr.forEach(num => {         freqMap.set(num,                  (freqMap.get(num) || 0) + 1);     });      return arr.sort((a, b) => {         if (freqMap.get(a) !== freqMap.get(b)) {             return freqMap.get(a)                          - freqMap.get(b);         } else {             return a - b;         }     }); }  const arr = [3, 3, 1, 1, 1, 8, 3, 6, 8, 8]; console.log("Sorted by increasing frequency using Map :",                         sortInFreq(arr)); 

Output
Sorted by increasing frequency using Map : [   6, 1, 1, 1, 3,   3, 3, 8, 8, 8 ] 

Time Complexity: O(n log n)

Space Complexity: O(n)


Next Article
Sort an array of objects using Boolean property in JavaScript
author
bug8wdqo
Improve
Article Tags :
  • JavaScript
  • Web Technologies

Similar Reads

  • Generate Random Number in Given Range Using JavaScript
    Here are the different ways to generate random numbers in a given range using JavaScript 1. Using Math.random(): basic ApproachThis is the simplest way to generate a random number within a range using Math.random(). [GFGTABS] JavaScript let min = 10; let max = 20; let random = Math.floor(Math.random
    3 min read
  • Sort an array of objects using Boolean property in JavaScript
    Given the JavaScript array containing Boolean values. The task is to sort the array on the basis of Boolean value with the help of JavaScript. There are two approaches that are discussed below: Table of Content Using Array.sort() Method and === OperatorUsing Array.sort() and reverse() MethodsUsing a
    2 min read
  • Find Mode of an Array using JavaScript
    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 , 3Ou
    4 min read
  • JavaScript - Sort a String Alphabetically using a Function
    Here are the various methods to sort a string alphabetically using a function in JavaScript. 1. Using split(), sort(), and join() MethodsThis is the most basic and commonly used method to sort a string alphabetically. The string is first converted into an array of characters, sorted, and then joined
    3 min read
  • Count Frequency of an Array Item in JavaScript
    Here are the different approaches to count the frequency of an Array Item in JavaScript Using a Loop and CounterThis is the most basic and efficient approach when you want to find the frequency of a single item. You simply loop through the array and count how many times the item appears. [GFGTABS] J
    2 min read
  • How to create a Number object using JavaScript ?
    In this article, we will discuss how to create a Number object using JavaScript. A number object is used to represent integers, decimal or float point numbers, and many more. The primitive wrapper object Number is used to represent and handle numbers. examples: 20, 0.25. We generally don't need to w
    2 min read
  • JavaScript program to print even numbers in an array
    Given an array of numbers and the task is to write a JavaScript program to print all even numbers in that array. We will use the following methods to find even numbers in an array: Table of Content Method 1: Using for Loop Method 2: Using while Loop Method 3: Using forEach LoopMethod 4: Using filter
    5 min read
  • 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
    2 min read
  • Sort An Array Of Arrays In JavaScript
    The following approaches can be used to sort array of arrays in JavaScript. 1. Using array.sort() Method- Mostly UsedJS array.sort() is used to sort and update the original array in ascending order. [GFGTABS] JavaScript let arr = [[3, 2], [1, 4], [2, 5], [2, 0]]; arr.sort(); console.log(arr); [/GFGT
    2 min read
  • Sort Array of Objects By String Property Value in JavaScript
    Sorting arrays of objects based on a string property can be helpful for handling user data or dynamic lists. Here are different ways to sort an array of Objects By String Property Value. 1. Using localeCompare() Method – Most UsedThe JavaScript localeCompare() method returns a number indicating whet
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences