Answers for "sort a dict by key in js"

3

sort a dictionary by value in javascript

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')
})
Posted by: Guest on August-09-2021
1

sort from the key value js

var masterList = [
    { key: 1, val: "google" },
    { key: 2, val: "yahoo" },
    { key: 3, val: "msn" },
    { key: 4, val: "stackoverflow" },
    { key: 5, val: "github" },
    { key: 6, val: "jsfiddle" },
    { key: 7, val: "amazon" },
    { key: 8, val: "ebay" }
];

masterList.sort((a,b)=> (a.val < b.val ? 1 : -1)) //For Decending

masterList.sort((a,b)=> (a.val > b.val ? 1 : -1)) //For Ascending

console.log( masterList );
Posted by: Guest on April-05-2022

Code answers related to "Javascript"

Browse Popular Code Answers by Language