Determine the frequency of duplicate elements in an array and arrange them in descending order based on their frequency

After making an API call, my array is populated with values like this:

["9777", "9777", "2.4", "9777", "2.4", "2.4", "9777", "2.4", "2.4", "9777", "9777", "2.4", "2.4", "2.4"]

My goal is to count the occurrences of each item in the array and then sort them in descending order based on the count.

I found a solution on stackoverflow which suggests the following code:

data.forEach(function (x) {
  counts[x] = (counts[x] || 0) + 1;
});

While this code works, it produces strange results that make it challenging to extract the desired values. Here is an example of the results obtained: https://i.sstatic.net/bKVwT.jpg

Answer №1

An alternative approach involves utilizing the reduce function to tally and construct an object containing the counts, followed by using the sort function.

If there is a need to single out a specific object based on its "name", the find function can be employed:

let array = ["9777", "9777", "2.4", "9777", "2.4", "2.4", "9777", "2.4", "2.4", "9777", "9777", "2.4", "2.4", "2.4"],
    counts = Object.values(array.reduce((a, c) => {
      (a[c] || (a[c] = {name: c, count: 0})).count += 1;
      return a;
    }, {})).sort(({count: ac}, {count: bc}) => bc - ac),
    target = "2.4",
    found = counts.find(({name}) => name === target);

console.log(counts);
console.log(found);
console.log(found.count);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

To begin, start by compiling a distinct list of items and then iterate through this list to append them to the final outcome.

Once the list has been generated, organize it by utilizing the count key that was established during the previous step.

const items = ["9777", "9777", "2.4", "9777", "2.4", "2.4", "9777", "2.4", "2.4", "9777", "9777", "2.4", "2.4", "2.4"];

// Declaring a variable to store the results
const result = [];

// Create a unique list of items to iterate over
// Append each item to the result list
[...new Set(items)].forEach(item => result.push({
  key: item,
  // Calculate the number of occurrences of the current item
  count: items.filter(i => i == item).length
}));

// Sort the array in descending order of item occurrence
result.sort((a, b) => b.count - a.count);

console.log(result);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using cascading style sheets to switch a page into editing mode

Is it possible to change the view of a page after clicking a button without using javascript, and instead relying solely on CSS? I want to display a page with information where users can click an edit button and make changes within the same view rather th ...

Stop users from typing inside a newly inserted element in contenteditable mode

Currently, I am developing a straightforward syntax highlighter that transforms text into DOM elements with specified classes. For example, consider the following: <div contenteditable="true"> Some text. | And some other text. </div> Assum ...

Why does my node-js API's second endpoint not function properly?

Currently working on my first API project. Everything was going smoothly, until I encountered an issue with my second route, app.route('characters/:characterId'). For some reason, none of the endpoints are functioning, while the first route, app. ...

What is the proper way to access and modify the child component within a parent component?

I am working with nested components as shown below: app.parent.component > app.container.component > app.containeritem.component Here is an example: app.parent.component import ... @Component({ selector:'parent', template: &apos ...

Create a TypeScript view component that encapsulates an HTMLElement for seamless integration with TweenMax

Looking to develop my own basic view component class that encompasses an HTMLElement or JQuery element, I want to be able to do something similar to this: var newComponent:CustomComponent = new CustomComponent($('#someDiv')); TweenMax.to(newCom ...

The Functionality of Accordions

I have created a responsive accordion script that functions smoothly and allows for easy access to content within each drawer. Unlike many accordions, this one does not cause issues with positioning after opening. The code I am using includes a toggle acti ...

How to Convert JSON from an Object to a String using jQuery?

Currently, I am utilizing the Ajax Form jQuery plugin to fetch JSON data from a server: /** * A convenient function for the jQuery AJAX form plugin. */ function bindOnSuccess(form, callback) { form.ajaxForm({ dataType: 'json', ...

Tips for dynamically updating the name of a JSONObject

I'm working on a project that involves collecting user details through a series of dialogs. The goal is to capture these details and convert them into JSON format. Users have the option to enter details for multiple people, each of which should be con ...

Using jQuery in Angular, you can add a div element to hidden elements by appending

So, I have a hidden div that I want to show on button click. And not only do I want to show it, but I also want to append another div to it. The show and hide functionality is working fine, but the appending part seems tricky when dealing with hidden eleme ...

Error encountered while attempting to serialize React Fragment: Symbol value cannot be converted to a string

Encountering an issue while attempting to render a React.Fragment: Error Message: Cannot convert a Symbol value to a string Snippet of the code being passed to a component: render{ const block = { type : 'menu', className: &ap ...

Steps for correctly invoking a function based on input value conditions

Lately, I've been developing a new website geared towards serving as a platform for various travel agencies to showcase their tour packages. The homepage features a functional filter section that enables users to search for offers based on different ...

Enhancing AngularJS routing with dynamic partial parameters

I have experience working with routes in different frameworks like Rails and Laravel, but I am now facing a challenge while working on an AngularJS site. In Laravel, we could dynamically create routes using foreach loops to handle different city routes. Ea ...

7 Tips for Renaming Variables in VSCode without Using the Alias `oldName as newName` StrategyWould you like to

When working in VSCode, there is a feature that allows you to modify variables called editor.action.rename, typically activated by pressing F2. However, when dealing with Typescript and Javascript, renaming an imported variable creates aliases. For exampl ...

Combining numerous objects into one object within an array, each with distinct keys, and displaying them using FlatList

I'm struggling to present this information in a FlatList. Array [ Object { "-N1gqvHXUi2LLGdtIumv": Object { "Message": "Aeaaeaea", "Message_CreatedAt": 1652167522975, "Message_by_Ema ...

Utilizing AJAX to dynamically update a div on a separate webpage

In my application, I have a page called news.jsp that displays a list of news titles. Users can click on a title to read the full body of the news, which is loaded using AJAX within a span tag on the same page. Additionally, I display the top 5 news storie ...

What is the best way to incorporate a formArray into a formGroup?

Before anything else, I want to apologize for any errors in my English. I seem to be having trouble adding an array field to a formGroup. My issue arises when attempting to use the push method to add a formArray to my rate formGroup. It appears that the ...

Transform the Vue.js component into a Webpack component

I found this code in a tutorial and now I need to make some modifications so it can be compiled with Webpack, including the template script and CSS files. <html> <head> <title>VueJs Instance</title> <s ...

Issue with NodeJS: The HTTP GET request is returning the code instead of the expected JSON object

My NodeJS code is designed to fetch a JSON object from a website. Here is the snippet: var http = require('http'); var url = { host: 'www.sample-website.com', headers: { "Accept": "application/json", 'Content-Type&apos ...

Creating a like and dislike button using Jquery's ajax functionality

Hey everyone, I'm currently working on implementing a like and dislike button similar to Facebook's on my website. I have a list of posts displayed using PHP loops and I want a single button to change color to blue if liked and remain the default ...

When using the parseFloat function with a regular expression input, it results

My goal is to adjust float values within a string by a specific amount. Here is my current approach: var string = '<path d="M219.6,-71.4C249,19.1,212.7,130.9,135.7,186.8C58.8,242.7,-58.8,242.7,-135.7,186.8C-212.7,130.9,-249,19.1,-219.6,-71.4C-19 ...