Methods for organizing an array of objects by a specific key in JavaScript, but in the case of duplicate values, the objects can be sorted by a different

I'm struggling to sort an array of objects by two different keys. I need to first sort the array by price, and if there are multiple items with the same price, they should then be sorted by time. Here's what my array looks like:

var myArr = [
{"value":5 , "price"=10, "time":3},
{"value":1.5 , "price"=2, "time":2},
{"value":3 , "price"=5, "time":4},
{"value":1 , "price"=2, "time":1}
]

After sorting, the array should look like this:

var myArr = [
{"value":1 , "price"=2, "time":1},
{"value":1.5 , "price"=2, "time":2},
{"value":3 , "price"=5, "time":4},
{"value":5 , "price"=10, "time":3}
]

I've tried various methods but haven't been able to solve it due to the complexity of sorting by two keys simultaneously.

Answer №1

To achieve sorting by price and then by time, you can utilize the Array.sort method:

var myArr=[{value:5,price:10,time:3},{value:1.5,price:2,time:2},{value:3,price:5,time:4},{value:1,price:2,time:1}];

myArr.sort((a, b) => {
  return a.price - b.price || a.time - b.time;
});
console.log(myArr);

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

Obtain documents from one folder, analyze files in a different location, and then correlate files with their respective contents

Let me clarify by giving an example - I have a directory with images and another one with text files containing image information. I want to create an array where each image is matched with its corresponding data in another array. I am feeling overwhelmed ...

Tips for merging two applications into a single file using Node.js

This code snippet represents the functionality of my chat application. var worker = function(worker) { var http = require('http'); var fs = require('fs'); var app = http.createServer(function(request, response) { f ...

The CKEditor is having trouble properly opening code snippets

I have been using ckeditor 4.4 along with the code snippet plugin. Initially, when I create a document with a rich code snippet and save it, everything works perfectly fine. The source code for what is generated looks like this: <pre><code>&am ...

Iterating through a JSON object to verify the presence of a specific value

I have a JSON Object and I am looking for a way in Angular 6 to search for the value "Tennis" in the key "name". Can you provide guidance on how to achieve this? { "id":2, "name":"Sports", "url":"/sports" "children":[ { "id":1, ...

Developing in Java Script with ENVDTE involves adding a new project to an existing solution and placing it in a designated sub-folder for organization purposes

Currently, I am working on developing a Visual Studio extension for a new C++ project template using Visual Studio 2010. The approach I am taking involves utilizing the .vsz template method and customizing the default.js code to suit my requirements. Withi ...

When transferring an object from a blade template to a Vue component through props, it may become undefined

I'm facing an issue where I am attempting to send an array from an asynchronous method in the controller to a Vue component using props within a blade template. However, when I try to log it in the Vue component, it shows up as undefined. Here is the ...

Transform my Curl script into a NodeJS app

I'm trying to replicate the functionality of a curl command within my NodeJS application, but I am facing some difficulties. Any guidance on how to achieve this would be greatly appreciated. curl -H "Authorization: bearer $TOKEN" If I already hav ...

Utilize time in submitting a form

Is it possible to schedule a form submission at a specific time, such as 12:00? I have already created a countdown timer and now would like the form to be submitted automatically at a certain time. <html> <head> </head> <body> ...

Why do I keep getting undefined when I use React.useContext()?

I'm currently using Next.js and React, employing react hooks along with context to manage state within my application. Unfortunately, I've encountered a perplexing issue where React.useContext() is returning undefined even though I am certain tha ...

Is it necessary to download all npm packages when starting a new project?

I recently started learning about npm packages and node. I noticed that when installing packages, they create numerous folders in the "node modules" directory. This got me thinking - when starting a new project, do I need to re-install all these packages ...

Angular routes cause a glitch in the Bootstrap navbar, causing it to shift to the left on certain active

Apologies for the simple question, I am new to web design and couldn't find a solution even after extensive googling and searching. The issue I am facing is that when clicking on "EX5" or "EX6" in my navbar, it shifts to the left side of the screen i ...

Using Ajax.Updater to run JavaScript code

I've tried numerous online tutorials and examples, but haven't had much success... I'm looking to execute JavaScript from an HTML Response in Ajax. Here's my code snippet: <script src="prototype.js" type="text/javascript"></ ...

The position of the scroll bar remains consistent as you navigate between different websites

Is it possible for me to click on a link within my HTML website and have the other website load with me in the exact same position? For example, if I'm halfway down a webpage and click a link, can I be taken to that same point on the new page? If so, ...

Scroll to the top of a new page with Material UI's table component

Feeling a little stuck here. I've tested various settings with scrollTop, but haven't had much luck. To clarify, I'm working with Material UI and their pagination features in conjunction with a table (you can find the documentation here). W ...

After my jQuery functions are executed, my CSS rules are loaded

Struggling with the communication between CSS and jQuery, I find myself torn. In CSS, my rules are often very specific, like this: div#container > div#contentLeft { //Code here } However, when I add jQuery to spice up my site, the CSS rules seem to ...

Having trouble with dynamic path generation for router-link in Vuejs when using a v-for loop?

//main.js import Vue from "vue"; import App from "./App.vue"; import VueRouter from "vue-router"; import HelloWorld from "./components/HelloWorld.vue"; Vue.use(VueRouter); const router = new VueRouter({ routes: [{ path: "/", component: HelloWorld }] } ...

Tips for retrieving the location of a draggable waypoint in the Google Directions output

<!DOCTYPE html> <html> <head> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Location Partner</title> <!--styles for ...

What is the best method for eliminating script tags from a Magento web store's source code?

Below is the source code for the Magento site's homepage. I am looking to eliminate all JavaScript links from the code: ...

The function insertAdjacentHTML does not seem to be functioning properly when used with a

I am working with a parent element that contains some child elements. I create a DocumentFragment and clone certain nodes, adding them to the fragment. Then, I attempt to insert the fragment into the DOM using the insertAdjacentHTML method. Here is an ex ...

Changing the font family for a single element in Next.js

One unique aspect of my project is its global font, however there is one element that randomly pulls font families from a hosted URL. For example: https://*****.com/file/fonts/Parnian.ttf My page operates as a client-side rendered application (CSR). So, ...