0

im trying to sort an array with many object, but i can how to sort only the first value. this is my exemple code: https://jsfiddle.net/v6wc8ufg

Im trying to do the SQL order by value1, value2,value3

var myArray = [
  { id: 'a', val: '4', city: 'Spain' },
  { id: 'a', val: '1', city: 'Paris' },
  { id: 'z', val: '5', city: 'London' },
  { id: 'z', val: '4', city: 'Rome' },
  { id: 'b', val: '9', city: 'Italy' }
];

function SortByName(a, b) {
  var aName = a.id;
  var bName = b.id;
  return aName < bName ? -1 : aName > bName ? 1 : 0;
}

myArray.sort(SortByName);
michael
  • 4,053
  • 2
  • 12
  • 31
bolzy9
  • 31
  • 5
  • Do you want sort by first by `id`, then by `val`? You can do something like this: `myArray.sort((a,b) => a.id.localeCompare(b.id) || a.val - b.val)` – adiga Dec 04 '20 at 08:15

2 Answers2

0

You should check sex value in the timing of returning 0 value for sort function, which means id is same.

  return ((aName < bName) ? -1 : ((aName > bName) ? 1 : (a.sex < b.sex) ? -1 : (a.sex > b.sex) ? 1 : 0));
wangdev87
  • 8,611
  • 3
  • 8
  • 31
0

I hope this one helps.

const sortFunc = (a, b) => {
    if (a.value1 !== b.value1) return a.value1 > b.value1 ? 1 : -1;
    if (a.value2 !== b.value2) return a.value2 > b.value2 ? 1 : -1;
    ...

    return 0;
}