I have the following code, which seems to be doing the correct thing, but when I log the array object it never changes:
let data = [
{'country': 'AB', 'state': 'DE'},
{'country': 'US', 'state': 'CA'},
{'country': 'AB', 'state': 'DE'},
{'country': 'US', 'state': 'MI'},
{'country': 'RU', 'state': null}
];
function sortFunc(a, b) {
let val = a['country'] < b['country'];
console.log(a['country'], b['country'], val);
return +val;
}
data.sort(sortFunc);
console.log(data);
What is the issue with the above code?
The sort function needs to go both ways and return 0 if equal or -1 or 1 -- the above function just returns 1 or 0. Here would be a proper version:
let data = [
{'country': 'AB', 'state': 'DE'},
{'country': 'US', 'state': 'CA'},
{'country': 'AB', 'state': 'DE'},
{'country': 'US', 'state': 'MI'},
{'country': 'RU', 'state': null}
];
function sortFunc(_a, _b) {
let [a,b] = [_a['country'], _b['country']];
if (a===b) return 0;
else if (a>b) return 1;
else return -1;
}
data.sort(sortFunc);
console.log(data);
I don't know whether you want to sort it in ascending or descending, so just figure it out yourself from ternary operator. Rest I guess its working as you expect.
let data = [
{'country': 'AB', 'state': 'DE'},
{'country': 'US', 'state': 'CA'},
{'country': 'AB', 'state': 'DE'},
{'country': 'US', 'state': 'MI'},
{'country': 'RU', 'state': null}
];
function sortFunc(a, b) {
return a['country'] < b['country']?1:-1;
}
data = data.sort(sortFunc);
console.log(data);