Elo
0
Q:

sort array of objects javascript

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
8
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
list.sort((a, b) => (a.color > b.color) ? 1 : -1)
2
By default, the sort() method sorts the values as strings in alphabetical and ascending order.
This works well for strings ("Apple" comes before "Banana"). However, if numbers are sorted as strings, "25" is bigger than "100", because "2" is bigger than "1".
Because of this, the sort() method will produce an incorrect result when sorting numbers.
You can fix this by providing a "compare function"

numbers = [2, 3, 41, 3, 2, 4, 5];

numbers.sort(function(a,b){return a-b});

// For more info on the compare function see https://www.w3schools.com/jsref/jsref_sort.asp
11
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
elems.sort((a, b) => a.id - b.id);
1
function sortByDate( a, b ) {
  if ( a.created_at < b.created_at ){
    return -1;
  }
  if ( a.created_at > b.created_at ){
    return 1;
  }
  return 0;
}

myDates.sort(sortByDate);//myDates is not sorted.
8

var points = [40, 100, 1, 5, 25, 10];

points.sort(function(a, b){return a-b});

 
8

New to Communities?

Join the community