Sorting objects in an array according to their prices: A guide

Suppose we have the following data structure:

var lowestPricesCars =
{
  HondaC:
  {
    owner: "",
    price: 45156
  },
  FordNew:
  {
    owner: "",
    price:4100
  },
  HondaOld:
  {
    owner: "",
    price: 45745
  },
  FordOld:
  {
    owner: "",
    price: 34156
  },
}

How can I sort the cars based on their prices?

If you need clarification on the question, feel free to leave a comment.

Thank you!

Answer №1

const keysArray = Object.keys(listOfLowestPrices)
const sortedKeysByPrice = keysArray.sort((a,b) => {
  return listOfLowestPrices[a].price - listOfLowestPrices[b].price;
});
let carsSortedByPrice = {}
sortedKeysByPrice.forEach(key => carsSortedByPrice[key] = listOfLowestPrices[key])

To reverse the order:

return listOfLowestPrices[b].price - listOfLowestPrices[a].price;

Answer №2

If you want to accomplish this task efficiently, you can use ES6 features such as Object.entries, Array.sort, and Array.reduce.

It's important to note that the order of object keys is not guaranteed and may vary between different browsers, so relying on it is not recommended.

const data = { HondaC: { owner: "", price: 45156 }, FordNew: { owner: "", price:4100 }, HondaOld: { owner: "", price: 45745 }, FordOld: { owner: "", price: 34156 } }

console.log(Object.entries(data)
  .sort((a,b) => a[1].price - b[1].price)  // for DESC b[1].price - a[1].price
  .reduce((r,[k,v]) => (r[k] = v, r), {}))

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

How can I generate codegen types using typeDefs?

I have been exploring the capabilities of graphql-codegen to automatically generate TypeScript types from my GraphQL type definitions. However, I encountered an issue where I received the following error message: Failed to load schema from code file " ...

Why does the control skip the onreadystatechange function for the ajax object?

Just beginning my journey into web-development. Recently, I encountered an issue with a signup page I created that involves asynchronous calls to php. Upon debugging, I noticed that the onreadystatechange function is being completely skipped over. Any assi ...

Preventing CSRF Errors when activating API endpoints in Node Express JS by ensuring that bypassing the error message with next() function is ineffective

In this middleware block, I have implemented a mechanism to render a 404 page when an invalid CSRF token is detected. /* * Middleware for rendering 404 page on invalid csrf token */ this.app.use((err: any, req: Request, res: ...

Looping through properties of objects with the help of angularJS ng-repeat is known as using objects['propertyname&#

What is the best way to iterate over an object with property names like this? $scope.myobjects = [ { 'property1': { id: 0, name: 'someone' } }, { 'property2': { id: 1, name: ' ...

Alternative Options for Playing Audio in Internet Explorer 8

I'm in the process of setting up a button that can both play and pause audio with a simple click. While this functionality is working smoothly in modern browsers like Google Chrome, I am facing compatibility issues with IE 8. Even after attempting to ...

Generating a bullet list from an array of objects

Looking to create an unordered list with vanilla JS, using an array of objects to populate the list. Struggling a bit on how to accomplish this. Here is my current code: let myObj = [ {name: "Harry Potter", author: "JK Rowling"}, {name: "Hunger Gam ...

Utilizing Bootstrap Modal to Display PHP Data Dynamically

Modals always pose a challenge for me, especially when I'm trying to work with someone else's code that has a unique take on modals that I really appreciate (if only I can make it function correctly). The issue arises when the modal is supposed ...

Looking for a slideshow with interactive play buttons?

Looking for a slideshow similar to the one on the homepage of this site: Has anyone ever used a slideshow like that before? Any other references or help would be appreciated! ...

Tips on implementing Dynamic arrays in the useEffect hook within React applications

Does anyone have experience with using a dynamic array as input in the dependency array of the useEffect hook? I'm encountering an issue where the array is being passed as a string and therefore not triggering the hook correctly. const [formData,setFo ...

Upgrading email functionality: Combining PHP mail() with AJAX

My issue revolves around using the mail() function. When AJAX code is present, the email gets sent but without any message (the subject is intact though). However, when I remove the AJAX code, the email goes through without any problems. I'm not well ...

jquery unable to retrieve element

I have implemented a piece of code that adds the 'nav-pills' class to an element with the class 'nav-tabs' when the window width is less than 768px. $(window).on('resize', function () { $('.nav-tabs').toggleClass(&a ...

The order of items in MongoDB can be maintained when using the $in operator by integrating Async

It's common knowledge that using {$in: {_id: []}} in MongoDB doesn't maintain order. To address this issue, I am considering utilizing Async.js. Let's consider an example: const ids = [3,1,2]; // Initial ids retrieved from aggregation con ...

"After clicking the button for the second time, the jQuery on-click function begins functioning properly

(Snippet: http://jsfiddle.net/qdP3j/) Looking at this HTML structure: <div id="addContactList"></div> There's an AJAX call that updates its content like so: <div id="<%= data[i].id %>"> <img src="<%= picture %&g ...

The embedded iframe on YouTube is displaying the incorrect video

I am currently designing a website and I want to feature a video on the homepage. The video is hosted on YouTube and I need to embed it into my website. <html> <iframe width="560" height="315" src="https://www.youtube.com/embed/spPdelVEs_k?rel= ...

Automatically Resizing an iFrame Height Upon Submit Button Click

Currently, I am facing an issue with a form that generates an iFrame for the Payment section. While the height of the iFrame is set correctly, whenever there are errors in the form submission and error messages appear, they push the submit button below t ...

obtain an inner element within a container using the class name in a div

I am attempting to locate a span element with the class of main-tag within a nested div. However, I want to avoid using querySelector due to multiple elements in the HTML file sharing the same class and my preference against using IDs. I realize there mig ...

Checking for mobile SSR in a ReactJS applicationUncover the signs of mobile

I recently integrated the mobile-detect library into my project following this informative tutorial: link /src/utiles/isMobile.tsx: import MobileDetect from "mobile-detect"; import { GetServerSidePropsContext } from "next"; export co ...

Calculate the number of days required for the value in an item to multiply by two

I'm currently working on a JavaScript project to create a table displaying the latest number of coronavirus cases. I've reached a point where I want to add a column showing how many days it took for the confirmedCases numbers to double. Here&apos ...

Is it possible to remove the "disabled" attribute using JS, but the button remains disabled?

There are two buttons on my page: the first one is currently disabled, and the second one is supposed to enable the first button. That's the plan. Button 1: $(document).ready(function() { $('#click').click(function() { document.getE ...

Issue with close request on dialog box

Whenever an icon is clicked, a dialog box containing a form should appear. The purpose of this dialog box is to either add a new tab or delete a specific tab. In my implementation, I used ReactJS, Redux, and Material-UI for building the components. Even th ...