Q:

js sort array of object by key

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'}
16
arr.sort((x, y) => x.distance - y.distance);
6
let orders = [
  { 
    order: 'order 1', date: '2020/04/01_11:09:05'
  },
  { 
    order: 'order 2', date: '2020/04/01_10:29:35'
  },
  { 
    order: 'order 3', date: '2020/04/01_10:28:44'
  }
];


console.log(orders);

orders.sort(function(a, b){
  let dateA = a.date.toLowerCase();
  let dateB = b.date.toLowerCase();
  if (dateA < dateB) 
  {
    return -1;
  }    
  else if (dateA > dateB)
  {
    return 1;
  }   
  return 0;
});

console.log(orders);
5
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"}
2
function sortByKey(array, key) {
  return array.sort((a, b) => {
    let x = a[key];
    let y = b[key];
    
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
  });
}
2
/**
 * Function to sort alphabetically an array of objects by some specific key.
 * 
 * @param {String} property Key of the object to sort.
 */
function dynamicSort(property) {
    var sortOrder = 1;

    if(property[0] === "-") {
        sortOrder = -1;
        property = property.substr(1);
    }

    return function (a,b) {
        if(sortOrder == -1){
            return b[property].localeCompare(a[property]);
        }else{
            return a[property].localeCompare(b[property]);
        }        
    }
}
1
myArray.sort(function(a, b) {
    return a.distance - b.distance;
});
0

New to Communities?

Join the community