skip to Main Content

I want to sort this JSON array based on unitId

var array = [
{ id: 10, unitId: 'unit17' }, 
{ id: 11, unitId: 'unit19' },
{ id: 13, unitId: 'unit27' }, 
{ id: 12, unitId: 'unit2' }, 
{ id: 13, unitId: 'unit11' },
{ id: 14, unitId: 'unit1'}
];

I want an output array like this

var array = [
{ id: 14, unitId: 'unit1' }, 
{ id: 12, unitId: 'unit2' }, 
{ id: 13, unitId: 'unit11' }, 
{ id: 10, unitId: 'unit17' },
{ id: 11, unitId: 'unit19'},
{ id: 13, unitId: 'unit27' }
];

2

Answers


  1. To sort the given array based on the alphanumeric unitId, you can use the sort() method with a custom comparator function. Here’s an example:

    var array = [
      { id: 10, unitId: 'unit17' },
      { id: 11, unitId: 'unit19' },
      { id: 13, unitId: 'unit27' },
      { id: 12, unitId: 'unit2' },
      { id: 13, unitId: 'unit11' },
      { id: 14, unitId: 'unit1' }
    ];
    
    array.sort((a, b) => {
      const unitIdA = parseInt(a.unitId.replace('unit', ''), 10);
      const unitIdB = parseInt(b.unitId.replace('unit', ''), 10);
      return unitIdA - unitIdB;
    });
        
    console.log(array);
    

    This will output the desired sorted array:

    [
      { id: 14, unitId: 'unit1' },
      { id: 12, unitId: 'unit2' },
      { id: 13, unitId: 'unit11' },
      { id: 10, unitId: 'unit17' },
      { id: 11, unitId: 'unit19' },
      { id: 13, unitId: 'unit27' }
    ]
    

    The sort() function takes a custom comparator that compares two elements a and b. The unitId values are first stripped of the ‘unit’ string and then converted to integers using parseInt(). The difference between the unitId integers is returned to determine the sort order.

    Login or Signup to reply.
  2. You can also use regex combination by replacing all non-digit numbers with empty string and then compare it.

    var array = [
    { id: 10, unitId: 'unit17' }, 
    { id: 11, unitId: 'unit19' },
    { id: 13, unitId: 'unit27' }, 
    { id: 12, unitId: 'unit2' }, 
    { id: 13, unitId: 'unit11' },
    { id: 14, unitId: 'unit1'}
    ];
    
    let sorted = array.sort((a,b) => a.unitId.replace(/D/g,'') - b.unitId.replace(/D/g,''))
    
    console.log(sorted)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search