Answers for "sort an object javascript"

26

sort array of object js

const books = [
  {id: 1, name: 'The Lord of the Rings'},
  {id: 2, name: 'A Tale of Two Cities'},
  {id: 3, name: 'Don Quixote'},
  {id: 4, name: 'The Hobbit'}
]

books.sort((a,b) => (a.name > b.name) ? 1 : ((b.name > a.name) ? -1 : 0));
Posted by: Guest on April-08-2021
15

sort by object property javascript

let list = [
  {
      name: "world"
  },
  {
      name: "hello",
  },
];

// This doesn't account for if names are the same between objects
let x = list.sort((a, b) => (a.name > b.name ? 1 : -1));

console.log(x);

/*
[
  {
      name: "hello",
  },
  {
      name: "world"
  },
];
*/
Posted by: Guest on August-23-2020
1

javascript sort object js

grossaryList = {
  'bread': 1,
  'apple': 6,
  'milk': 1, 
  'orange': 3,
  'broccoli': 2 
}

return Object
  .entries(grossaryList)
  .sort((a,b) => b[1]-a[1])

//=> [['apple', 6],['orange', 3],['broccoli', 2],['bread',1],['milk', 1]]
Posted by: Guest on April-27-2021
3

javascript sort object by key

function sortObjectByKeys(o) {
    return Object.keys(o).sort().reduce((r, k) => (r[k] = o[k], r), {});
}
var unsorted = {"c":"crane","b":"boy","a":"ant"};
var sorted=sortObjectByKeys(unsorted); //{a: "ant", b: "boy", c: "crane"}
Posted by: Guest on August-02-2019
1

sort objects in array js

function createDropDowns() {
    for (const [key, val] of Object.entries($pgns["nmea2000"])) {
      pgnList = [...pgnList, val];
      fieldsList[val.title] = val.fields;
      fieldsListOut[val.title] = val.fields;
    }
    pgnList.sort((a, b) =>
      a.title > b.title ? 1 : b.title > a.title ? -1 : 0
    );
}

pgnList = [
  	{pgn: '065280', manufacturer: '161', title: 'Proprietary - Set Serial Number', fields: Array(6), route: '/nmea2000/data/{busNumber}/by_instance/{instance}/065280/{field}'}
	{pgn: '065280', manufacturer: '257', title: 'Engine Status Parameters, Dynamic', fields: Array(10), route: '/nmea2000/data/{busNumber}/by_instance/{instance}/065280/{field}'}
	{pgn: '065284', manufacturer: '257', title: 'Display Communication Status', fields: Array(12), route: '/nmea2000/data/{busNumber}/by_instance/{instance}/065284/{field}'}
	{pgn: '065289', manufacturer: '161', function: '1', title: 'Proprietary - Set Volume and Capacity', fields: Array(8), …}
	{pgn: '065289', manufacturer: '161', function: '2', title: 'Proprietary' }
]
Posted by: Guest on September-30-2021
3

sorting of arraray's number element in javascript

let numbers = [0, 1, 2, 3, 10, 20, 30];
numbers.sort((a, b) => a - b);

console.log(numbers);
Posted by: Guest on April-17-2020

Code answers related to "sort an object javascript"

Code answers related to "Javascript"

Browse Popular Code Answers by Language