Determine the frequency of each element in an array and arrange them in ascending order

In my quest to locate occurrences of numbers within an array, I aimed to display the numbers and their respective frequencies in ascending order. Here is what I was trying to achieve:

let arr = [9,-10,2,9,6,1,2,10,-8,-10,2,9,6,1];

// {'-10': 2, '-8': 1, '1': 2, '2': 3, '6': 2, '9': 3, '10': 1}

To accomplish this task, I stored the occurrences of each number in an object. However, upon logging the numCount object, I noticed that while all the numbers were sorted in ascending order, the negative numbers did not follow suit.

/*Find occurrences*/
let numCount = {};
for(let num of arr){
    numCount[num] = numCount[num] ? numCount[num] + 1 : 1;
}
console.log(numCount);
//{ '1': 2, '2': 3, '6': 2, '9': 3, '10': 1, '-10': 2, '-8': 1 }

I researched how to sort objects and learned that one method involved storing them in an array and then sorting it. So, I attempted the following approach:

/*Store them in array and then sort it*/
let sortedArray = [];
for(let item in numCount){
    sortedArray.push([item, numCount[item]]);
}
sortedArray.sort(function(a,b){
    return a[0] - b[0];
});

/*
console.log(sortedArray);
[
  [ '-10', 2 ],
  [ '-8', 1 ],
  [ '1', 2 ],
  [ '2', 3 ],
  [ '6', 2 ],
  [ '9', 3 ],
  [ '10', 1 ]
]
*/

However, the resulting sortedObject displayed the negative numbers at the end, similar to the initial state. This is the hurdle I am currently facing.

let sortedObject = {};
sortedArray.forEach(function(item){
    sortedObject[item[0]] = item[1];
})
/*console.log(sortedObject);
{ '1': 2, '2': 3, '6': 2, '9': 3, '10': 1, '-10': 2, '-8': 1 }
*/

Here is the full code snippet:

let arr = [9,-10,2,9,6,1,2,10,-8,-10,2,9,6,1];

/*Find occurrences*/
let numCount = {};
for(let num of arr){
    numCount[num] = numCount[num] ? numCount[num] + 1 : 1;
}

/*Store them in array and then sort it*/
let sortedArray = [];
for(let item in numCount){
    sortedArray.push([item, numCount[item]]);
}
sortedArray.sort(function(a,b){
    return a[0] - b[0];
});


let sortedObject = {};
sortedArray.forEach(function(item){
    sortedObject[item[0]] = item[1];
})

console.log(sortedObject);

Answer №1

Rules are in place for the sorting of keys/properties within an object, ensuring they are reliably ordered as long as you understand these rules.

If a property resembles a positive number (in reality, all properties are actually strings even if they appear to be numbers), it will be sorted in ascending order. Otherwise, it will maintain the order of insertion. But how does the object determine if a property value is similar to a number or not?

Let's take key '9': initially, it is converted into the number 9, then back to a string '9' - just like the original value. This categorizes it as a positive number-similar value.

Now, let's consider key '-10': when converted to a number, it becomes -10.

As it is not positive, it is considered a string... and this logic applies to the rest as well.

Hence, it becomes evident that sorting for properties resembling positive numbers was not truly necessary. Regardless of whether the input array is sorted or not, the outcome remains consistent due to the established rules.

solution:

When handling key '09': after being turned into the number 9, it differs from the initial value upon conversion back to a string. Hence, it is categorized as a string.

Therefore, a '0' should be added before every numeric-like property to convert and sort it accordingly.

sortedArray.forEach(function(item){
    let key = parseInt(item[0])>0 ? '0'+item[0] : item[0]
    sortedObject[key] = item[1];
})
//{ "-10": 2, "-8": 1, 01: 2, 02: 3, 06: 2, 09: 3, 010: 1 }

Note that the behavior of parseInt varies for numbers like 010, assuming them to be Octal.

An alternative and more effective solution involves using map - explore Maps and their distinctions from Objects further here.

Answer №2

Consider utilizing a Map, which could enable you to achieve your desired functionality with the object while also allowing you to define a specific key order.

let numbers = [9,-10,2,9,6,1,2,10,-8,-10,2,9,6,1];

/*Count occurrences*/
let numCounter = new Map();
for(let number of numbers){
  numCounter.set(number, (numCounter.get(number) ?? 0) + 1);
}

let sortedNumberMap = new Map([...numCounter.entries()].sort((a, b) => a[0] - b[0]));

console.log(sortedNumberMap.get(-10));
console.log(...sortedNumberMap.keys());
console.log(...sortedNumberMap.values());

Answer №3

Object properties do not have a guaranteed order, and how an object is displayed can vary depending on the specific implementation of console.log.

If it happens to be solely a matter of display, one approach could be:

const sortedArray = [[-10, 2], [-8, 1], [1, 2], [2, 3], [6, 2], [9, 3], [10, 1]];

let result = `{${sortedArray.map(el => `'${el[0]}': ${el[1]}`).join(', ')}}`;

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

What are some methods for controlling a webpage? Is it through HTML, JavaScript, Xpath, or

Hey there, I could really use your expertise on untangling a question that has me completely stumped. What exactly is the mechanism for controlling a webpage? a. HTML b. JavaScript c. Xpath d. CSS ...

Leveraging JavaScript Functionality with ASP.NET Identity Roles

I'm currently working on an application that utilizes JQuery DataTables. The goal is to have these tables visible to all users, but restrict the click functionality to a specific user role. One way I can achieve this is by setting up authorization on ...

How can I conceal the element that came before in JavaScript?

<div onclick="toggleContent(this)" class="iptv"><div class="triangle"></div><b>LUZ HD</b> - 98 channels (including 32 HD channels) <div class="iptv_price"><b><img src="img/rj45.png" class="icon_ofert ...

Renaming ngModel in an AngularJS directive's "require" attribute can be achieved by specifying a different alias

I need help with a basic AngularJS directive: <my-directive ng-model="name"></my-directive> I want to change the "ng-model" attribute to "model", but I'm unsure how to pass it to the "require" option in the directive. Here is the full co ...

Using Typescript with Angular 2 to Implement Google Sign-In on Websites

Currently, I am in the process of creating a website that utilizes a typical RESTful web service to manage persistence and intricate business logic. To consume this service, I am using Angular 2 with components coded in TypeScript. Instead of developing m ...

Looking for a feature where users can easily update their profile using an interactive edit button

I'm currently working on a website project and one of the features I'm tackling is the user's profile page. My objective is to create an edit button within the page that allows the user to modify their name, username, email, and update their ...

Click on the header to activate the accordion link with a trigger

I am having an issue with a trigger. My goal is to make the accordions collapse not only by clicking on the link, but also by clicking on the entire header panel. Below is my header's code: <div class="accordion-head" role="tab"> <div cl ...

Ensure that all links are opened in a new tab

When including _blank in the a href URL, my website contains various elements like iframes and ads from Adsense, Taboola,, etc. Currently, when a user clicks on an iframe or ad, it opens in the same window. Is there a way to ensure that all URLs (includin ...

Sort ng-repeat based on the initial character

Working in AngularJS, I am handling an array of objects and aiming to display filtered data based on the first letter. My initial method used was as follows. HTML: <p ng-repeat="film in filmList | startsWith:'C':'title'">{{film. ...

Continue to run upon clicking the button in the Document Object Model

I want the code to constantly change instead of executing only once. By default, the button has a dark mode for text and the background color is pink. When you click the button, the background color changes to black and the text in the button turns into li ...

Material-UI icons refusing to show up on the display

I've been working on creating a sidebar component and importing various icons to enhance the UI, but for some reason they are not displaying on the screen. I even tried other suggested solutions without success. <SidebarOption Icon = {InsertComment ...

Can you explain how to utilize a function on a client component in Next.js?

I'm a bit lost on how client components function. I am working on an image uploader project where I need to extract the userId from supabase, utilize the supabase server function, and then upload the image to supabase storage with the "userId/filename ...

Deleting elements from an array of objects in Angular Would you like help with

I have a JSON structure and I need to remove the entire StartGeotag object from the array. [{ CreatedDate: "2022-02-17T10:30:07.0442288Z" DeletedDate: null ProjectId: "05b76d03-8c4b-47f4-7c20-08d9e2990812" StartGeotag: { ...

What is the most effective method for emptying an array in this particular scenario?

In my programming project, I am working on creating a multidimensional array using a loop. The approach I am considering involves populating elements into a single array within the loop and then transferring that single array into a larger array before cle ...

Transferring JSON data from controller to view in CodeIgniter

After making an API call, I received the response in JSON format: JSON: { "Specialities": [ { "SpecialityID": 1, "SpecialityName": "Eye Doctor" }, { "SpecialityID": 2, "SpecialityName": "Chiropractor" }, { ...

Navigating to a new page once a backend function in Express has finished executing

Recently, I have been experimenting with express web servers to create a website that allows users to sign in using Discord's OAuth2 API. In order to secure sensitive information, I have been utilizing the express-session npm module to store data with ...

Transfer data in scripts to dynamically load Ajax pages

Is there a way to send variables or parameters from the original page to a script tag on another page that is loaded using jQuery Ajax? Here are the scripts: Page 1 <script> $(function(){ $('#button').click(function(){ $.ajax({ type:"P ...

Discovering the highest value in MongoDB

Good Morning! I am currently working with a MongoDB structure that looks like this: { "_id": 19, "name": "Fredia Donan", "faculty": "Zoomzone", "lectures": [ { &qu ...

In Javascript, a function is executed only once within another function that is set on an interval

Using the Selenium Chrome driver in my JavaScript, I am constantly checking a value on a website every 2 seconds. However, I need to only save status changes to a text file, not every single check. The current code is functional but it saves the text fil ...

Are the digest cycle and dirty checking synonymous terms?

I have a question that's been bugging me lately. Can you clarify for me if the digest loop (also known as digest cycle) in AngularJS is synonymous with dirty checking? And if they are different, could you please explain the distinctions between them? ...