Answers for "sort object js"

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
5

sort array of objects javascript

list.sort((a, b) => (a.color > b.color) ? 1 : -1)
Posted by: Guest on July-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
17

javascript sort array of objects

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'}
]

compareObjects(object1, object2, key) {
  const obj1 = object1[key].toUpperCase()
  const obj2 = object2[key].toUpperCase()

  if (obj1 < obj2) {
    return -1
  }
  if (obj1 > obj2) {
    return 1
  }
  return 0
}

books.sort((book1, book2) => {
  return compareObjects(book1, book2, 'name')
})

// Result:
// {id: 2, name: 'A Tale of Two Cities'}
// {id: 3, name: 'Don Quixote'}
// {id: 4, name: 'The Hobbit'}
// {id: 1, name: 'The Lord of the Rings'}
Posted by: Guest on February-25-2020

Code answers related to "Javascript"

Browse Popular Code Answers by Language