Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

how to sort an array of objects by two fields in javascript

var data = [{ h_id: "3", city: "Dallas", state: "TX", zip: "75201", price: "162500" }, { h_id: "4", city: "Bevery Hills", state: "CA", zip: "90210", price: "319250" }, { h_id: "6", city: "Dallas", state: "TX", zip: "75000", price: "556699" }, { h_id: "5", city: "New York", state: "NY", zip: "00010", price: "962500" }];

data.sort(function (a, b) {
    return a.city.localeCompare(b.city) || b.price - a.price;
});

console.log(data);
Comment

javascript sort array of objects multiple fields

array.sort(function(a,b){
  let i = 0, result = 0;
  while(i < sortBy.length && result === 0) {
    result = sortBy[i].direction*(a[ sortBy[i].prop ].toString() < b[ sortBy[i].prop ].toString() ? -1 : (a[ sortBy[i].prop ].toString() > b[ sortBy[i].prop ].toString() ? 1 : 0));
    i++;
  }
  return result;
})
Comment

PREVIOUS NEXT
Code Example
Javascript :: js check if is array 
Javascript :: iterate over list array in solidity 
Javascript :: sort javascript number array with duplicates 
Javascript :: @angular/common@11.2.1 node_modules/@angular/common @angular/common@"11.2.1" from the root project 
Javascript :: change span value javascript 
Javascript :: sanitizing user input javascript 
Javascript :: layout nextjs 
Javascript :: scroll to div js 
Javascript :: Access to XMLHttpRequest has been blocked by CORS policy node js 
Javascript :: capitalize first letter of string javascript 
Javascript :: C:fakepath fileupload 
Javascript :: check if key does not exists in dictionary javascript 
Javascript :: vuex add multiple payload to mutation 
Javascript :: react native strike through text 
Javascript :: redux devtools extension 
Javascript :: how to get class name in jquery 
Javascript :: javascript break foreach 
Javascript :: how to make apk of react native app 
Javascript :: react index.jsx example 
Javascript :: slide out navigation 
Javascript :: loop an object in javascript 
Javascript :: react function being called every minute 
Javascript :: jquery set hidden field value 
Javascript :: react input number validation 
Javascript :: react js marked import and use 
Javascript :: chrome extension open new tab from popup 
Javascript :: webpack sass 
Javascript :: event.preventdefault is not a function jquery 
Javascript :: virtual dom explained 
Javascript :: how to get a toggle button to do different js functions 
ADD CONTENT
Topic
Content
Source link
Name
9+9 =