Organizing an array of items based on their attributes

I am currently facing a challenge with sorting an array of objects by their values. In order to achieve this, I am using the following code:

function compare(a,b){return dict[a]-dict[b]}
 Object.keys(dict).sort(compare)

This implementation works perfectly when all values are unique. However, when two objects share the same value, the sorting leaves them in their original order instead of arranging them alphabetically as I desire. Unfortunately, I have not been able to find a solution to address this issue.

The initial object {a:1, d:4, c:2, b:4, e:5, f:3} should be sorted as follows:

{a:1, c:2, f:3, b:4, d:4, e:5 }

But the current output that I am getting is:

{a:1, c:2, f:3, d:4, b:4, e:5 }

Answer №1

To enhance the compareFunction, consider incorporating localeCompare

dict[a] - dict[b] || a.localeCompare(b)

If the result of dict[a] - dict[b] is 0, it will then evaluate the keys alphabetically in the sorting process.

Check out this example snippet:

const dict = {a:1, d:4, c:2, b:4, e:5, f:3}

function compare(a, b) {
  return dict[a] - dict[b] || a.localeCompare(b)
}

const sorted = Object.keys(dict)
                      .sort(compare)
                      .reduce((acc, k) => (acc[k] = dict[k], acc), {})

console.log( sorted )

Answer №2

To determine the order of keys, compare them and check if the difference is zero

function sortKeys(a, b) {
  var difference = dictionary[a] - dictionary[b];
  return difference === 0 ? a.localeCompare(b) : difference;
}

const dictionary = {
  apple: 1,
  banana: 4,
  carrot: 2,
  cherry: 4,
  orange: 5,
  pear: 3
};

const sortedResult = Object.keys(dictionary).sort(sortKeys).reduce((obj, key) => ({
  ...obj,
  [key]: dictionary[key]
}), {});

console.log(sortedResult);

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

Creating a Halo (external outline) for a circular sector in THREE.JS

I'm working on adding a halo (external black outline) to certain shapes in three.js. While I was able to achieve this easily with rectangles and circles, I am facing challenges with circular sectors (not full circles). Here is my current attempt: It ...

Extract a property from a JSON object

Is there a way to access the href properties and use them to create multiple img elements with their sources set as the extracted href properties? I'm looking for a solution in either javascript or jQuery. I attempted the following code, but it didn& ...

Exploring TypeScript Decorators and the Intricacies of Circular Dependencies

Take a look at this code snippet that involves inter-dependent code using decorators. Let's walk through the workflow where the actual classes are passed for later use: The application imports and executes Parent.ts @Test(Child) triggers the import ...

Caution in React: Utilizing functions with Object.assign() may not be a valid approach when dealing with React children

I have a setup using react for front-end and node for back-end. My goal is to retrieve data from the server to update the user entries on the front-end. I came across using Object.assign() as a potential solution to re-render user entries, but encountered ...

Turn off the ability to view the content of .css and .js files within the browser

Earlier, I inquired about how to disable file and folder listing and discovered that it can be achieved using a file named .htaccess. To disable folder listing, I entered Options -Indexes in the .htaccess file located in the parent folder. Additionally, to ...

Tips for downloading a file in React using raw file data

I've been struggling with a particular issue for the past couple of days and just can't seem to find a solution. It involves retrieving data from an API on our outdated system related to Attachments and other information. When I execute the query ...

Is the popup not opening with just one click?

https://i.stack.imgur.com/09dcf.png Upon clicking the first input cell, the popup opens and closes as expected. However, when closing the initial input and opening another one, an orange mark icon appears but the popup doesn't open until the second c ...

Managing a two-dimensional array in AngularJS: tips and tricks

I have a JSON source that provides me with a double array: // Function and module code omitted .. $scope.texts = [ ['Small sheep and ham.'], ['Ducks go moo.', 'Helicopters and racecars go bang!'] ]; My goal is to display ...

The vertexUv in three.js is currently undefined and needs to be

I'm currently facing an issue while trying to combine multiple meshes, one of which is created by inputting the vertices coordinates. This specific mesh is causing the following error: THREE.DirectGeometry.fromGeometry(): Undefined vertexUv 256 W ...

Is it possible to create two separate Express sessions simultaneously?

I am encountering an issue with my Passport-using application that has a GraphQL endpoint and a /logout endpoint. Strangely, when I check request.isAuthenticated() inside the GraphQL endpoint, it returns true, but in the /logout endpoint, it returns false. ...

Unravel the base64 encoded message from JavaScript and process it in Python

I'm currently facing an issue in Python while trying to decode a string sent by jQuery. Although I am not encountering any errors, I receive an encoding error when attempting to open the file. My objective is to decode the string in order to save it ...

Access an external URL from JSON data simply by utilizing VueJS

I am currently facing a challenge with linking to external URLs. The URL is extracted from JSON and connected to an HTML tag, but I am unable to retrieve the data and link it to the URL when clicking on images. HTML <section class="bg-light page-secti ...

What is the best approach to dynamically implement useReducer in code?

Take a look at the repository here: https://github.com/charles7771/ugly-code In the 'Options' component, I am facing an issue where I am hardcoding different names for each reducer case instead of dynamically generating them for a form. This app ...

Automatically adjusting the height of an iFrame using jQuery

Is there a way to automatically adjust the height of my iframe based on its content? I've successfully achieved this using a jQuery plugin called jquery-iframe-auto-height by house9. Now, I want the homepage within the iframe to fill the entire heigh ...

Having difficulty executing the playwright tests

Trying to execute the playwright test from the specified location results in a message prompting to run npm install -D @playwright/test before running the test. Despite having already installed playwright as a dev dependency, the test is still not being ex ...

Sliding down with a delay using jQuery

I'm attempting to create a hidden div that slides down when a button is clicked and then waits for about five seconds before sliding back up. I've experimented with using delay(), but I'm unsure if I'm applying it correctly. Additionall ...

Try incorporating "vector.applyQuaternion" or a similar method in your code within ammo.js

I'm eager to develop a virtual reality shooting game for browsers, utilizing Three.js and Ammo.js for the physics engine and rigid bodies. Although I've successfully set up the VR headset, controllers, and loaded models, I encountered an issue wi ...

What is the best way to specify a function parameter as a Function type in TypeScript?

I'm currently delving into the world of TypeScript and I am unsure about how to specify a function parameter as a function type. For instance, in this piece of code, I am passing a setState function through props to a child component. const SelectCity ...

The module 'PublicModule' was declared unexpectedly within the 'AppModule' in the Angular 4 component structure

My goal is to create a simple structure: app --_layout --public-footer ----public-footer.html/ts/css files --public-header ----public-header.html/ts/css files --public-layout ----public-layout.html/ts/css files In public-layout.html, the stru ...

Creating a dynamic list filter using JavaScript and three select boxes

Looking for a way to implement a similar feature to the one on this webpage: I will be showcasing a list of brands on the page, with each brand requiring three pieces of information: Starting letter Store (multiple options) Category (multiple options) ...