What is the most effective method for organizing an object by its values using multiple keys?

I'm interested in utilizing the sort method mentioned in the link but I am facing

{
  "CYLINDER": 2986,
  "HYDRAULIC": 1421,
  "JACKS": 84,
  "INSTALLATION": 119,
  "REAR": 61,
  "JACK": 334,
  "TUBE": 1,
  "FEED": 114,
  "ASSEMBLY": 326,
  "DCS": 2,
  "TOWER": 65,
  "RAISING": 8,
  "BREAKOUT": 6,
}

I have devised this function that groups similar strings together and assigns a count for each (shown as values in the key-value pairs above)

function calculateDuplicateOccurrences(wordArray) {
  const countedWords = wordArray.reduce(function(allWords, word) {
    if (word in allWords) {
      allWords[word]++;
    }
    else {
      allWords[word] = 1;
    }
    return allWords;
  }, {});
  return countedWords;
}

Despite my efforts on Google and Stackoverflow, I haven't come across a solution to sort by value when the keys are not unique. Any suggestions on how to address this issue?

The desired outcome looks like this:

{
  "TUBE": 1,
  "DCS": 2,
  "BREAKOUT": 6,
  "RAISING": 8,
  "REAR": 61,
  "TOWER": 65,
  "JACKS": 84,
  "FEED": 114,
  "INSTALLATION": 119,
  "ASSEMBLY": 326,
  "JACK": 334,
  "HYDRAULIC": 1421,
  "CYLINDER": 2986
}

Answer №1

To achieve the desired outcome, you can utilize Object.keys() and map in the following manner.

const data = {
  "TANK": 587,
  "ENGINE": 291,
  "BELT": 73,
  "FILTER": 58,
  "GAUGE": 123,
  "VALVE": 490,
  "HOSE": 33,
  "PUMP": 222,
  "SENSOR": 88,
  "MOTOR": 135,
  "CABLE": 76,
};

var newData = {};
Object.keys(data).sort(function(a,b){return data[a]-data[b]})
                 .map(key => newData[key] = data[key]);
console.log(newData);

Answer №2

To efficiently copy key-values, it is recommended to use Object.entries along with a forEach loop instead of the map method.

As pointed out by epascarello, using an actual array is preferable over relying on the key order in an object.

const list = {
  "CYLINDER": 2986,
  "HYDRAULIC": 1421,
  "JACKS": 84,
  "INSTALLATION": 119,
  "REAR": 61,
  "JACK": 334,
  "TUBE": 1,
  "FEED": 114,
  "ASSEMBLY": 326,
  "DCS": 2,
  "TOWER": 65,
  "RAISING": 8,
  "BREAKOUT": 6,
},newList = {}

Object.entries(list).sort((a,b) => a[1]-b[1])
  .forEach(elm => newList[elm[0]] = elm[1])

console.log(newList);

Answer №3

To start, you must convert the properties of your objects into an array structured like this:

[
   {name: "CYLINDER", quantity: 2986},
   {name: "HYDRAULIC", quantity: 4421}
   // and so on
]

Once you have transformed your object properties into an array, you can then use the sort method.

var input = {
  "CYLINDER": 2986,
  "HYDRAULIC": 1421,
  "JACKS": 84,
  "INSTALLATION": 119,
  "REAR": 61,
  "JACK": 334,
  "TUBE": 1,
  "FEED": 114,
  "ASSEMBLY": 326,
  "DCS": 2,
  "TOWER": 65,
  "RAISING": 8,
  "BREAKOUT": 6,
};

var result = Object.keys(input)
                   .map( x => ({name:x, quantity:input[x]}))
                   .sort( (a,b) => a.quantity - b.quantity);
console.log(result);

Answer №4

According to the reference provided in the documentation, the sort method requires a comparison function as an argument. To sort an array of objects by their INSTALLATION key, you can use the following code snippet:

array.sort(function(a,b) {return a.INSTALLATION - b.INSTALLATION})

Answer №5

Merge Object.keys(obj) with the .sort() method and utilize .map

const obj = {
  "CYLINDER": 2986,
  "HYDRAULIC": 1421,
  "JACKS": 84,
  "INSTALLATION": 119,
  "REAR": 61,
  "JACK": 334,
  "TUBE": 1,
  "FEED": 114,
  "ASSEMBLY": 326,
  "DCS": 2,
  "TOWER": 65,
  "RAISING": 8,
  "BREAKOUT": 6,
}

var sorted = {};

console.log("Un-sorted", obj);

Object.keys(obj).sort().map(function(key){
  sorted[key] = obj[key];
});

console.log("Sorted", sorted)

There may be a more elegant solution out there, but this approach gets the job done.

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

Accessing elements from a controller in a nested ng-repeat in AngularJS

I am relatively new to the world of AngularJS and I've encountered a challenge that I can't seem to figure out. The issue lies within my nested ng-repeat view, as I have a nested comment system. Therefore, the view is built from an object structu ...

Implementing an Angular theme in a project using Node.js, MySQL, and Express

I'm a beginner with node, angular, and express. I've managed to create a REST API using node+express+mysql, but now I need help integrating the blur-admin theme into my existing project. Despite getting the theme to run separately with gulp, I&ap ...

Adding multiple text as label and sublabel in a React MUI Tooltip can be achieved by utilizing the appropriate

I'm struggling to incorporate a MaterialUI Tooltip into my React application with two separate text lines. The first line should serve as the main title, while the second line functions as a sublabel. In this screenshot provided, you can see where I ...

The JavaScript confirm function will provide a false return value

Is it necessary to display a confirmation message asking "Are you sure ..."? I have implemented the message, but the function return false; is not working when the user clicks NO. <script> function confirmDelete(){ var answer = confirm("Are you su ...

Ways to ensure that ng-click is triggered exclusively on the click event

I am a beginner in Angular and attempting to toggle a class on click only for the current link. However, when I click, it is affecting all links instead of just the current one. I would like it to work only on the current element, similar to how we use "(t ...

The Jenkins build on a specific branch is encountering issues with path exporting, causing it to fail

I have a set of files related to a new feature that I am trying to deploy through Jenkins. I have successfully deployed other branches in the past, but I am encountering difficulties with a specific branch. I believe the problem may be related to the use ...

Is it advisable for postcss plugins to list postcss as a peer dependency?

I'm trying to incorporate the PostCSS Sass Color Function into my project. Unfortunately, I encountered this error: PostCSS plugin error: Your current version of PostCSS is 6.0.22, while postcss-sass-color-functions requires 5.2.18. This discrepa ...

suggestions for customizing Angular Material

The guidelines regarding materials specify that: "For any Angular Material component, you are allowed to define custom CSS for the component's host element that impacts its positioning or layout, such as margin, position, top, left, transform, and z- ...

Having trouble getting two different filters to work properly when filtering data in AngularJs

I have created a plunkr to demonstrate my current situation: The user is required to type a word into the textbox, and upon clicking the button, an angular service retrieves data from a DB based on the input text. The retrieved data is then displayed in a ...

Having difficulty sending emails with Nodemailer

This is a simple example showcasing the usage of Nodemailer library. var http = require('http'); var port = process.env.PORT || 8080; var async = require('async'); var nodemailer = require('nodemailer'); // Creating a transp ...

Utilizing a React Hook to set data by creating a pure function that incorporates previous data using a thorough deep comparison methodology

I have come across the following code snippet: export function CurrentUserProvider({ children }) { const [data, setData] = useState(undefined); return ( <CurrentUserContext.Provider value={{ data, setData, }} & ...

Tips for sending functions from client to server in Node.js

I'm working with this code snippet: const http = require('http'); const fs = require('fs'); const handleRequest = (request, response) => { response.writeHead(200, { 'Content-Type': 'text/html' ...

What is the best way to determine if a variable exists within an array in Angular and JavaScript?

Currently, I am working on a project using Angular 6 with Laravel. In one part of my code, I am fetching an array in the frontend and need to check if a certain variable is present within that array. In PHP, you can easily achieve this using the in_array f ...

Encountering Issues with Formatting InnerHtml Text using RegEx

Technology: React.js I have been working on a custom function in JavaScript to highlight specific words within a code block. The function seems to be functioning correctly, but the highlighting isn't staying after the function is completed. Any ideas ...

``Is there a way to retrieve the file path from an input field without having to submit the form

Currently, I am looking for a way to allow the user to select a file and then store the path location in a JavaScript string. After validation, I plan to make an AJAX call to the server using PHP to upload the file without submitting the form directly. Thi ...

Django DRF functions properly, however it returns an error when sending a response to an AJAX request

Successfully implemented an AJAX request using PUT in DRF. All functionalities are functioning correctly except for the error callback being triggered: DRF section: class ProductDataViewSet(viewsets.ViewSet): authentication_classes = [SessionAuthentic ...

Running Selenium tests are not able to initiate Javascript ajax requests

I'm currently troubleshooting a scenario using Selenium that involves the following steps: - When a user inputs text into a textarea, an ajax request is sent, which then adds the text to the database (implemented using django and processed in view.py) ...

What is the best way to retrieve widget options when inside an event?

Creating a custom jQuery widget: jQuery.widget("ui.test",{ _init: function(){ $(this.element).click(this.showPoint); }, showPoint: function(E){ E.stopPropagation(); alert(this.options.dir); } } Initializing the cu ...

HTML/PHP/JS - Submit Form and Upload File Simultaneously

I need to create a form with a Photo Upload Input that allows users to upload pictures before submitting the form for faster processing. The form should also support uploading multiple files, display a progress bar, and provide a preview of the uploaded im ...

Limiting multiple checkbox inputs in a React application can be easily achieved by utilizing React

Trying to create a form where the user can only check three boxes and uncheck them. The decrement on setCurrentData(currentData - 1) is not working as expected. Even after deselecting, the currentData remains at 3, preventing the user from checking any mo ...