JohnM
0
Q:

javascript sort array of object by property

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"
  },
];
*/
2
function compareFirstNames( a, b ) {
  if ( a.first_name < b.first_name ){
    return -1;
  }
  if ( a.first_name > b.first_name ){
    return 1;
  }
  return 0;
}

var people =[
    {"first_name":"Carol", "age":29},
    {"first_name":"Anna", "age":32},
    {"first_name":"Bob", "age":32}
];

people.sort( compareFirstNames ); //people is now sorted by first name from a-z
4
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

New to Communities?

Join the community