Home > database >  How to sort an array in Javascript by two non-mandatory properties?
How to sort an array in Javascript by two non-mandatory properties?

Time:02-03

I have this array:

arr = [
  { name: 'This one',number: '67', codes:['B33', '45']}
  { name: 'Another', number: '003', codes: ['55', 'A47']},
  { name: 'Something', codes:['A33']},
  { name: 'One more', number: '003'},
  { name: 'Anything',number: '67', codes:['A33']},
];

I want to order it first by "number" and then by "codes" in in ascending order, but both are not required and "codes" is an array of string.

The result should be:

arr = [
  { name: 'Something', codes:['A33']},
  { name: 'One more', number: '003'},
  { name: 'Another', number: '003', codes: ['55', 'A47']},
  { name: 'Anything',number: '67', codes:['A33']},
  { name: 'This one',number: '67', codes:['B33', '45']}
];

I tried to follow this code bellow, but it's not working for my case:

 orderIt(){
        return arr.sort((a, b) => 
            a.number- b.number || a.codes - b.codes;
         );
    }

(source)

Explaining why my question is different: In the other questions, both are required and there aren't an array of string inside of it.

CodePudding user response:

You could check if the property extist and take the delta to move this items to top.

const
    array = [{ name: 'This one', number: '67', codes: ['B33', '45'] }, { name: 'Another', number: '003', codes: ['55', 'A47'] }, { name: 'Something', codes: ['A33'] }, { name: 'One more', number: '003' }, { name: 'Anything', number: '67', codes: ['A33'] }];

array.sort((a, b) =>
    ('number' in a) - ('number' in b) ||
    ('codes' in a) - ('codes' in b) ||
    a.number - b.number ||
    (a?.codes?.[0] || '').toString().localeCompare(b?.codes?.[0] || '')
);

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

CodePudding user response:

const a = [
  { name: 'Something', codes:['A33']},
  { name: 'One more', number: '003'},
  { name: 'Another', number: '003', codes: ['55', 'A47']},
  { name: 'Anything',number: '67', codes:['A33']},
  { name: 'This one',number: '67', codes:['B33', '45']}
];


const b = a.sort((a, b) => {
  const an = a.number || '';
  const bn = b.number || '';
  const ac = (a.codes || []).join('');
  const bc = (b.codes || []).join('');
  

  return (an   ac).localeCompare(bn   bc);
});

console.log(b);

  •  Tags:  
  • Related