sort.js 463 B

1234567891011121314151617181920
  1. let persons = [
  2. {name: "Иван", age: 17},
  3. {name: "Мария", age: 35},
  4. {name: "Алексей", age: 73},
  5. {name: "Яков", age: 12},
  6. ]
  7. const mySort = (arr, sortField, ascDesc = true) => {
  8. const sortFunc = (a, b) => {
  9. if (a[sortField] < b[sortField]){
  10. return ascDesc ? -1 : 1;
  11. }
  12. return ascDesc ? 1 : -1;
  13. }
  14. return arr.sort(sortFunc);
  15. };
  16. console.log(mySort(persons, 'age'));
  17. console.log(mySort(persons, 'name', false));