Is there a way to use the property of an object to perform a merge sort, rather than relying on an Array?

Query About Sorting JSON Object in JavaScript

In search of the most efficient method to sort a large JSON object based on a specific property, I turned to JavaScript. My initial thought was to utilize a merge sort algorithm for this task due to its speed. However, if there is a faster alternative available, I am open to suggestions. While examples of merge sorts on arrays are abundant online, resources on how to apply them to objects are scarce. Below is a simplified representation of the JSON object in question:

fruitForSale = {
     1: {"type":"orange","UnitPrice":0.20},
     2: {"type":"banana","UnitPrice":0.30},
     3: {"type":"pear","UnitPrice":0.10},
     4: {"type":"apple","UnitPrice":0.50},
     5: {"type":"peach","UnitPrice":0.70}
}

Sorting Challenge

If opting for a merge sort or any other quicker algorithm, how could I rearrange the fruitForSale object to be ordered by 'type' as shown below:

   fruitForSale = {
                     4: {"type":"apple","UnitPrice":0.50},
                     2: {"type":"banana","UnitPrice":0.30},
                     1: {"type":"orange","UnitPrice":0.20},
                     5: {"type":"peach","UnitPrice":0.70},
                     3: {"type":"pear","UnitPrice":0.10}                  
                   }

Please note that the original keys (1,2,3,4 & 5) must remain linked to their corresponding objects. Consequently, key 1 should always align with

{"type":"orange","UnitPrice":0.20}
, key 2 with
{"type":"banana","UnitPrice":0.30}
, and so forth.

Your insights would be greatly appreciated!

Answer №1

If you're looking to sort the keys of an object, one way to achieve this is by maintaining your own array of sorted keys.

var fruitForSale = {
     1: {"type":"orange","UnitPrice":0.20},
     2: {"type":"banana","UnitPrice":0.30},
     3: {"type":"pear","UnitPrice":0.10},
     4: {"type":"apple","UnitPrice":0.50},
     5: {"type":"peach","UnitPrice":0.70}
},

sortedKeys = Object.keys(fruitForSale).sort(function (i,j) {
    return fruitForSale[i]["type"] > fruitForSale[j]["type"];
});

For a live example, you can check out this JSFiddle link (Output displayed on the console).

Note that while Object.keys may not be supported everywhere, you can always polyfill it if necessary. For more information, you can refer to the following link: Object.keys Polyfill.

And if you're interested in understanding how the sorting implementation works under the hood, feel free to explore this post: Javascript Array.sort implementation?

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

Fetching images stored on an external website and loading them into an iframe within an Electron application

I am contemplating turning my website into a desktop application using either an iframe or webview within an Electron app. My website contains numerous images that I wish to cache in the Electron app to prevent repeated downloads. Is it possible to access ...

Having trouble with missing jQuery form serialize data in CodeIgniter when using TinyMCE?

I have encountered an issue while using tinymce. I am sending data through a jQuery ajax call like this: // update textarea from tinymce tinyMCE.triggerSave (false,true); $.post ('', $('#page_form').serialize (), function (x){ var ...

Encountered an issue while attempting to start an SSR server with inertiajs

I followed all the necessary steps to set up an ssr application, but unfortunately, I am encountering some difficulties. config/inertia export const inertia: InertiaConfig = { view: 'app', ssr: { enabled: true, autoreload: process.en ...

"Implementing classes with AngularJS: A Step-by-Step Guide

Is there a way to dynamically add a class to the i tag after a button is clicked in AngularJS? <button type="button" title="Like" ng-click="countLikes(product.title)" class="btn btn-compare"> <i class="fa fa-thumbs-o-up"></i> </ ...

Retrieve data using ajax within an mvc framework

I am facing an issue where I am unable to receive the data sent with AJAX jQuery to a .NET server as a parameter, modify it in memory, and then convert it to JSON. Any assistance in resolving this problem would be greatly appreciated. JAVASCRIPT document ...

The <Link> component in NextJS is not functioning as anticipated

I am currently developing a Next.js application and I'm facing an issue with creating dynamic routes upon clicking a card component. Even after wrapping my Cards with the <Link> from Next.js, the page doesn't navigate when clicked. I experi ...

Find the most recent date in a file and display the line associated with it

I am working with a document named Application.txt that consists of multiple columns and rows as shown below: ApplNo DocsURL DocDate 4782 www…. 7/28/2003 4782 www…. 11/23/2008 4782 www…. 3/24/2012 5010 www…. 4/5/2003 5010 ww ...

Issue with Angular dropdown menu not showing the initial option

I am trying to set up a drop-down menu with the first item in the list appearing after it has been sorted by 'name' using the code snippet below: <h2 class="presentation site is-input-header">Site</h2> <div class="modal-select-ele ...

Troubleshooting Highcharts container selection problem on Nexus 7 running version 4.2.1

Having a problem with Highcharts on my Nexus 7. When I touch the chart, the entire thing gets selected with a blue overlay, but this doesn't happen on other devices like the Nexus 4. Even when I try accessing demos from Highcharts website, the issue ...

Enhancing jQuery Functionality with Parameter Overrides

While it may seem like a simple question, I am new to writing jQuery plugins and could use some clarity on scope rules in JavaScript. My goal is to create a jQuery plugin that interacts with the Stack Overflow API. I have started exploring the Flair API f ...

Creating a dynamic form where input fields and their values update based on user input in jQuery

In my form, I have an input field where users will enter an ISBN number. Based on the input number, I need to populate two other input fields: one for book title and one for author name. I am currently calling a JavaScript function on the onblur event of ...

Exploring ways to retrieve item metadata from a Stripe checkout session

When setting up a Checkout session, I dynamically create prices using the price_data and product_data properties. I include metadata for each item within the product_data.metadata property. However, after a successful payment is made, I retrieve the sessi ...

A guide on reading an external JSON file using React

I'm trying to integrate an external JSON file into my React app. To demonstrate what I'm aiming for, I've provided a functional example on Codesandbox.io: https://codesandbox.io/s/morning-tdd-we2v3?file=/src/App.js Currently, the example ...

using javascript to target a specific css selector attribute

I have a CSS file with the following code: .datagrid table tbody td { color: #00496B; border-left: 1px solid #E1EEF4; font-size: 16px ;font-weight: normal; } Is there a way to use JavaScript to dynamically change the font size? The code below worked ...

Is it possible to utilize Babel for transpiling, importing, and exporting in the client, all without relying on Web

Is it possible to compile JSX and export variables through the global namespace using Babel? I'm not interested in setting up a Webpack server. I'm currently familiarizing myself with ES6, JSX, Babel, and React, and I find adding another librar ...

Invalid Resize Argument Causes Background to Not Appear on IE Browser

I have encountered a problem where the background (BG) image is not appearing in Internet Explorer (IE). I am struggling to find a solution for this issue. BG Problem Below is the code snippet showing how I implemented the background image. I have used a ...

Tips on creating a search feature with JavaScript and AJAX

I'm currently facing an issue with my search functionality. I have successfully loaded data from a JSON file, but the search feature is not working as expected. I've reviewed my code multiple times and can't identify any mistakes. I believe ...

Enforcing character limits in summernote

Is there a way to set a character limit on Summernote? I've tried setting maxlength on the textarea without success. Check out the Summernote GitHub page $("#textareaid").summernote({ toolbar:[ ['style', ['style']], ...

The ng-disabled directive is functioning properly, however it is not having any impact on the disabled attribute in

Having an issue with enabling or disabling a button based on the selection of a certain string from a dropdown menu. HTML <select ng-change="checkType()" ng-options="sth in sth for things"></select> <input ng-disabled="{{toggleDisable}}" ...

Monitoring a specific property within an array of objects with AngularJS

I am facing an issue with the data in my controller $scope.data = { home: { baseValue: "1", name: "home" }, contact: { baseValue: "2", name: "contract" } // numerous ...