1

I buit this code to sort the array values acording to car value.

const arr = [
    {
        car: 'audi',
        age: 2015
    },
    {
        car: 'bmw',
        age: 1999
    },
    {
        car: 'alfa',
        age: 2019
    },
];
function createSort(property) {
    return function compareString(a,b) {
        return a[property] < b[property]
    }
}

const sortByTitle = createSort('car');
arr.sort(sortByTitle);

console.log(arr);

I can't figure out why it does not sort.
What is the issue?

Asking
  • 3,487
  • 11
  • 51
  • 106
  • 1
    To compare strings, use [*localeCompare*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare): `return a[property].localeCompare(b[property])`. There are a huge number of questions about [sorting using strings](https://stackoverflow.com/search?q=%5Bjavascript%5D+sort+strings). – RobG May 14 '20 at 09:15

4 Answers4

3

Short code:

arr.sort((x, y) =>x.car.localeCompare(y.car));

Full code:

const arr = [
    {
        car: 'audi',
        age: 2015
    },
    {
        car: 'bmw',
        age: 1999
    },
    {
        car: 'alfa',
        age: 2019
    },
];

let output = arr.sort((x, y) =>x.car.localeCompare(y.car));
console.log(output);
David
  • 15,894
  • 22
  • 55
  • 66
1

edit: @David answer seems a better way !

var arr = [
    {
        car: 'audi',
        age: 2015
    },
    {
        car: 'bmw',
        age: 1999
    },
    {
        car: 'alfa',
        age: 2019
    },
];



arr.sort(function(a, b){
  if(a.car< b.car) { return -1; }
  if(a.car> b.car) { return 1; }
  return 0;
})
console.log(arr)
ZecKa
  • 2,552
  • 2
  • 21
  • 39
0

Sort like below:

   const arr = [
      {
          car: 'audi',
          age: 2015
      },
      {
          car: 'bmw',
          age: 1999
      },
      {
          car: 'alfa',
          age: 2019
      },
    ];
    function createSort(property) {
      return function compareString(a,b) {
          return a[property] > b[property]
      }
    }

    const sortByTitle = createSort('car');
    arr.sort(sortByTitle);

    console.log(arr);
Aman
  • 828
  • 1
  • 10
  • 15
0

This is generic function which you can use,

    function createSort (field) {
      return function sort (data1, data2) {
      let value1 = data1[field]
      let value2 = data2[field]
      return (value1 == null && value2 != null) ? -1
      : (value1 != null && value2 == null) ? 1
        : (value1 == null && value2 == null) ? 0
          : (typeof value1 === 'string' && typeof value2 === 'string') ? value1.localeCompare(value2)
            : (value1 < value2) ? -1 : (value1 > value2) ? 1 : 0
     }
    }
Vikas Keskar
  • 1,158
  • 9
  • 17