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

Run JavaScript upon the webpage loading without the dependency of jQuery

Is there a way to ensure that JavaScript code is executed only after the entire page has loaded, without relying on jQuery? Take this example... <html> <head> <script type="text/javascript"> var box = document.ge ...

What is the best way to organize an array according to the positions of another array?

Currently, I am working with a tableView set to the style of Right Detail. To handle this setup, I have divided my data into two separate arrays: one for the main textLabels and another for the detailTextLabel. In this scenario, there are two sorting opti ...

Tips for Angular JS Single Page Applications: Implementing Angular Controllers to Invoke Angular Services

Currently, I'm in the process of building a Node.js Application using Angular.js and Express.js. My goal right now is to populate a list with customer names and addresses by using this code snippet: var mylist = new generic.list(); mylist.add({name ...

Tips for adjusting the close date based on the selected date in a dropdown datepicker

Here is a sample code snippet: <input id="date1" name="start_date" id="dpd1"/> <select class="form_line_only form-control" name="ho_night"> <option selected> 0 </option> <option ...

Guide to creating a dictionary array on-the-fly:

I have been working on updating years to make it more dynamic by using the starting year (2010) and ending year (2018). Originally, I used a for loop to address this, but I am curious if there is a more efficient way to refactor years. Current arrangemen ...

Utilizing AngularJS to display a table with Rowspan functionality and the ability to filter elements

I am trying to develop an HTML table that utilizes rowspan with ng-repeat to group data effectively. The overall layout is functioning as expected, but I encountered a problem when attempting to apply filters to the table. Specifically, when I filter the ...

Tips for efficiently updating an object's value without excessive code duplication

I'm struggling to find a solution for this issue. Currently, I have a jQuery object that creates a cookie. The problem arises when I need the cookie name to be something other than user-height. For example, in certain scenarios, I would prefer the co ...

The Javascript query is returning an [object Object] data type

I am facing an issue with a JavaScript file that is querying a SharePoint list. Specifically, the Priority drop down in the query result is displaying as [object OBJECT]. I suspect it has something to do with the var query string where I have added the &ap ...

Is there a way for me to increment the value of 'sessionStorage.fgattempt' whenever either 'fgMade()' or 'threeMade()' are called?

Currently, I am developing a basketball game stat tracker and need to update the field goal attempts every time I make a field goal or three-pointer. Additionally, I am looking for ways to optimize the javascript code provided. The main requirement is to ...

What is the best way to clear all input data that has been displayed in every input field within a React js application?

import React, { useState } from "react"; import axios, { Axios } from "axios"; import { ContainerDiv, InnerDiv, StyledButton, StyledInput, } from "./StyledComponents"; function WeatherCard() { const [input, SetInput ...

Choosing an item in an AngularJS select directive from an external origin

I'm currently working on developing a form using Angular JS for editing venue details such as address and city. The backend system is powered by Django and offers a REST API (Django Rest Framework) which I am interfacing with through Restangular serv ...

Pause the execution of an AJAX callback function after numerous AJAX requests

I have two separate Ajax calls in my code. Both of them have different callbacks that need to execute upon successful call. $.ajax({ type: 'POST', url: "url1", success: foo1 }); $.ajax({ type: 'POST', url: "url2", ...

Generate PHP arrays containing data on the number of orders and dates extracted monthly from an SQL database

I have a database table named 'orders' which contains multiple rows with different date entries. My objective is to create a visual representation in the form of a graph displaying the number of orders per month. To achieve this, I need to const ...

Tips on how to extract a boolean XML value for an orphan from a string

I am currently facing an issue while working with an API that returns XML data which I am having trouble retrieving. After a successful login, the session key is authenticated and the API responds with the boolean value 'true'. The format of th ...

Ways to transmit information among Vue components

I am trying to figure out how to pass data from the Module variable in CoreMods.vue to ExternalWebpage.vue using Vuex. I want the CoreModule state to be watched for changes in the external webpage. This is my store.js setup: import Vue from 'vue ...

Passing props from Vue3 to a component being rendered through RouterView

I'm facing an issue with the following code snippet: <template> <router-view /> </template> <script setup lang="ts"> ... const product: Ref<IProduct|undefined>: ref(); ... </script> The challenge is ...

Integrate data from Firebase into a React-Table component

I am currently working on a table component that fetches data from Firebase to populate three fields: Name Date Comment For each entry, I want to add a new row. The pivot has been successfully added. However, when trying to populate the table, I am encou ...

How can you generate an array of continuously updating data every 15 seconds in C#?

As a programming student, my current project involves utilizing a random number to represent a user-selected unit of measurement and then returning the measurement, converted value, and the time at which it was collected. To achieve this, I have implement ...

Parent Directory Injector: Prioritizing Injection of Parent Directories

Currently, I am utilizing 'grunt-injector' to inject a list of files using 'app/**/*.js'. However, I am facing dependency errors due to the alphabetical order in which the files are injected. To avoid these issues, I am looking for a so ...

Avoiding simultaneous connections when using socket.io during page redirection

I am currently developing a NodeJS application using Express and Socket.IO to direct the client-side script to redirect the user to another page based on specific conditions. The issue I'm encountering is that each redirection creates a new socket con ...