sort objects in javascript code example

Example 1: javascript sort array with objects

var array = [
  {name: "John", age: 34},
  {name: "Peter", age: 54},
  {name: "Jake", age: 25}
];

array.sort(function(a, b) {
  return a.age - b.age;
}); // Sort youngest first

Example 2: sort array of objects javascript

list.sort((a, b) => (a.color > b.color) ? 1 : -1)

Example 3: 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'}

Example 4: 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"}

Example 5: javascript sort object

var maxSpeed = {
    car: 300, 
    bike: 60, 
    motorbike: 200, 
    airplane: 1000,
    helicopter: 400, 
    rocket: 28800
};
var sortable = [];
for (var vehicle in maxSpeed) {
    sortable.push([vehicle, maxSpeed[vehicle]]);
}

sortable.sort(function(a, b) {
    return a[1] - b[1];
});

//[["bike", 60], ["motorbike", 200], ["car", 300],
//["helicopter", 400], ["airplane", 1000], ["rocket", 28800]]

Example 6: javascript sort array of objects

// Handles mix-cased strings and numbers with option for setting order
const sortObjectArray = ({ arr, field, order = 'desc' }) => {
   arr.sort(function(a, b) {
      const fieldA = typeof a[field] === 'string' ? a[field].toLowerCase() : a[field]
      const fieldB = typeof b[field] === 'string' ? b[field].toLowerCase() : b[field]

      let result
      if (order === 'desc') {
         result = fieldA > fieldB ? 1 : -1
      } else {
         result = fieldA < fieldB ? 1 : -1
      }
      return result
   })
   return arr
}

let arr = [
  {name: "John", age: 34},
  {name: "Peter", age: 54},
  {name: "jake", age: 25}
]

let arr2 = sortObjectArray({ arr, field: 'name'})
console.log(arr2)
/*
[
{ age: 25, name: "jake"}, 
{ age: 34, name: "John" }, 
{ age: 54, name: "Peter" }
]
*/

let arr3 = sortObjectArray({ arr, field: 'age', order: 'asc' })
console.log(arr3)
/*
[
{ age: 54, name: "Peter" },
{ age: 34, name: "John" }, 
{ age: 25, name: "jake"}
]
*/

Tags:

Cpp Example