A method of enumerating the elements of an array and arranging them in descending order

Collection:

5, 5, 5, 9, 4, 2, 2, 2, 2, 2, 3, 3, 3, 3

Desired Result:

2, 3, 5, 9, 4

Using array_count_values() and arsort() in PHP makes achieving this easy, but I'm facing challenges with implementing it in JavaScript. Any suggestions?


Additionally, is there a way to return the counts along with the elements for potential future requirements?

Answer №1

Identify distinct entries, form an array of distinct values, then arrange them based on frequency

function count(arr) { // calculate occurrences
    var obj = {}, index;
    for (index = 0; index < arr.length; ++index) {
        if (obj[arr[index]]) ++obj[arr[index]];
        else obj[arr[index]] = 1;
    }
    return obj;
}

function sortArray(arr_input) { // distinct values sorted by frequency
    var obj = count(arr_input),
        finalArr = [], index;
    for (index in obj) finalArr.push(+index); // quickly obtain distinct only
    finalArr.sort(function (a, b) {
        return obj[a] < obj[b];
    });
    return finalArr;
}

sortArray([1, 3, 3, 5, 5, 5, 2, 2, 2, 2]);
// one 1, two 3s, three 5s, four 2s
// [2, 5, 3, 1]

Your example includes both a 9 and a 4, so if you require a specific order, further adjustments would be needed. Otherwise;

sortArray([5, 5, 5, 9, 4, 2, 2, 2, 2, 2, 3, 3, 3, 3]);
// [2, 3, 5, 4, 9]

To generate an Array of Objects

function sortArray(arr_input) { // distinct values sorted by frequency
    var obj = count(arr_input),
        finalArr = [], index;
    for (index in obj) finalArr.push({value: +index, weight: obj[index]}); // quickly get distinct values only
    finalArr.sort(function (a, b) {
        return a.weight < b.weight;
    });
    return finalArr;
}

var result = sortArray([5, 5, 5, 9, 4, 2, 2, 2, 2, 2, 3, 3, 3, 3]);
/* [
    {"value": 2, "weight": 5},
    {"value": 3, "weight": 4},
    {"value": 5, "weight": 3},
    {"value": 4, "weight": 1},
    {"value": 9, "weight": 1}
] */

Now, to access the value at position i, use result[i].value, and for its weightage result[i].weight.

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

Exploring Bootstrap datatables to search through nested table data with Codeigniter

I have implemented a table using bootstrap datatables and successfully enabled search functionality within the table. However, I have also included nested tables within each row of the main table. These nested tables are supposed to be displayed when clic ...

The equivalent of e.preventDefault() in Java (for Android) is to replace the typed text

I am working on a jQuery/JavaScript function that will replace any text typed in an input field with a specific text. Here is the code snippet: $('input').on('keydown', function(e){ e.preventDefault(); count++; if (count == ...

After ReactDOM is used, the JavaScript code is no longer functioning properly

While working on my latest project, I utilized react.js and encountered an issue where javascript seemed to stop working when using ReactDOM to render a class extended from React.Component. I noticed that the alert() method would not work if it was placed ...

Which file should I include: npm-shrinkwrap.json, package-lock.json, or yarn.lock?

When shipping a package that is compiled only using tsc (the typescript compiler), I anticipate that consumers will install the necessary dependencies when they use npm or yarn to install my package. I aim to offer flexibility by not enforcing the use of ...

Understanding the performance of video in threejs when using getImageData

Edit; Check out the working codepen (you'll need to provide a video file to avoid cross-origin policy) https://codepen.io/bw1984/pen/pezOXm I'm currently trying to adapt the amazing rutt etra example from to utilize video (using threejs), but ...

"Fixing issue with Checkbox not getting checked using a combination of jQuery and

My array called `totalCheckBoxArray` contains the values [1, 2, 3]. I also have checkboxes with values 1, 2, and 3: <div class="card-body"> <h5>Document List</h5> <div class="form-check"> ...

Extract the element when the mouse is clicked

I'm currently working on developing a Chrome extension with a specific goal in mind: My aim is to capture the username when a user Ctrl-clicks on a username while browsing Reddit, and then transfer that username from the content script page to the ba ...

JavaScript - Problem transferring an object between two different JavaScript files

Welcome! I am just starting to learn JavaScript. Excuse me if I don't know all the technical terms yet. Scenario Currently, my project consists of three main files: index.html main.js sites.js index.html <body> <h ...

AngularJS Datepicker displaying incorrect dates

I have encountered an issue with the datepicker I am using (specifically AngularStrap's datepicker) where it seems to be consistently displaying a date that is one day behind due to how dates are calculated in javascript. My main concern is figuring o ...

Updating a Vue component following an axios POST request

I'm currently working with Laravel 8 and Vue 3. In my SessionComponent.vue, there's a button that triggers an axios post method when clicked. I want this action to display my StudentComponent.vue. Even though I attempted to use vue-router for th ...

Issue with mouseover functionality not functioning properly while hovering over a dropdown menu

My friend and I are relatively new to the world of coding with HTML, CSS, and a bit of JavaScript. We're currently facing an issue with our dropdown menu implementation. We have created buttons and added a dropdown menu using li and ul elements. Initi ...

If the element does not already exist, use jQuery to append it; otherwise, replace the existing element

Check out this snippet of code: const $element = $("#something").find(".test"); if (!$element.length) { $("#something").append('<div class="test">somecontent</div>'); } else { $element.replaceWith('<div class="test"&g ...

I'm puzzled as to why my Vuex modules are not functioning properly. I keep receiving the error message: "[vuex]

I've been searching for hours and can't figure out why I keep getting this error message: [vuex] unknown mutation type: groceryStore/getStoreApple on all of the commits to the mutations in the groceryStore-module. I believe I'm following the ...

In the Controller, the `getContent` function is configured to display only the token

When trying to send an array of objects in JSON format using AJAX, I'm facing an issue where only the token is being received when accessing $request->getContent. It appears that the data is not being sent properly. Can anyone assist me with this p ...

Testing Vue with Jest - Unable to test the window.scrollTo function

Is there a way to improve test coverage for a simple scroll to element function using getBoundingClientRect and window.scrollTo? Currently, the Jest tests only provide 100% branch coverage, with all other areas at 0. Function that needs testing: export de ...

Challenges with downloading a file synchronously using NodeJS

Having trouble with writing files synchronously in my local application using the 'download-file-sync' module. When I use 'writeFileSync', the file size doubles even though the content seems to be identical to a file downloaded through ...

Creating a Custom FlatList Content Container with React Native

Is it possible to customize FlatList items with a custom component? I want to create a setup where my FlatList items are encapsulated within a custom component similar to the following: <ScrollView pt={8} px={16} pb={128} > <Card e ...

Retrieve the value stored within an array object

I am dealing with the following data structure: var myValues = { 55bdf7bda89de40349854077: ["hello"] 55be0c77a89de403498540bc: ["goodbye"] 55be0e22a89de403498540c1: ["hey there!"] } Also, I have a variable that holds an id: var id = '55be0e ...

Searching for empty array fields in a jsonb column using a PostgreSQL query

device_id | device ----------------------------- 9809 | { "name" : "printer", "tags" : [] } 9810 | { "name" : "phone", "tags" : [{"count": 2, "price" : 77}, {"count": 3, "price" : 37} ] } When running a postgres SQL query on a jsonb column n ...

Updating MongoDB nested item by dynamic ID is a breeze

Hey there, I'm currently working on updating a nested Object in my MongoDB. The current structure looks like this: [ { "_id": "5871010d1ff9831574e7178d", "created_at": "2017-01-07T14:54:05.791Z", "updated_at": "2017-01-07T14:54:05.791Z", "p ...