I am trying to sort the keys of an object accoring to two conditons, first by having the word Current and then by Conv but I dont wont the last condition to undo the previous one.
const obj = {
'Additional Traffic': 2,
'Current Conv': 1,
'Additional Conv': 0.5,
'Current Rev': 100,
'Additional Rev': 50
}
const res = Object.keys(obj).sort((a, b) => a.includes('Current') && a.includes('Conv') ? -1 : 0)
// Expected output
// Current Conv
// Current Rev
// Additional Traffic
// Additional Conv
// Additional Rev
console.log(res)
>Solution :
usually you would have a function which compare using first criteria and if result is 0 (equality) you compare with next criteria.
So for you that would be:
const obj = {
'Additional Traffic': 2,
'Current Conv': 1,
'Additional Conv': 0.5,
'Current Rev': 100,
'Additional Rev': 50
}
const res = Object.keys(obj).sort((a, b) => {
let result = b.indexOf('Current') - a.indexOf('Current');
if (result === 0) {
result = b.indexOf('Conv') - a.indexOf('Conv');
}
return result;
});
// Expected output
// Current Conv
// Current Rev
// Additional Traffic <-- need one more rule for this one to be sorted properly
// Additional Conv
// Additional Rev
console.log(res)
Note that if you have a lot of words to check you can use an array like so:
const obj = {
'Additional Traffic': 2,
'Current Conv': 1,
'Additional Conv': 0.5,
'Current Rev': 100,
'Additional Rev': 50
}
const SORT_ARRAY = ['Current', 'Traffic', 'Conv'];
const res = Object.keys(obj).sort((a, b) => {
let sortCriteriaIdx = 0;
let result = 0;
while (result === 0 && sortCriteriaIdx < SORT_ARRAY.length) {
const criteria = SORT_ARRAY[sortCriteriaIdx];
result = b.indexOf(criteria) - a.indexOf(criteria);
sortCriteriaIdx++;
}
return result;
});
// Expected output
// Current Conv
// Current Rev
// Additional Traffic
// Additional Conv
// Additional Rev
console.log(res)