Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Order object keys by two conditions but give priority to the first one

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading