Home > front end >  Sort array based on last digit (as array values are seprated by _ )
Sort array based on last digit (as array values are seprated by _ )

Time:10-14

my array have is

let arr=['20336.41905.32121.58472_20336.41905.60400.51092_1',
'20336.41905.32121.58472_20336.41905.60400.48025_2',
'20336.41905.32121.58472_20336.41905.41816.60719_3',
'20336.41905.32121.58472_20336.41905.41816.63631_4',
'20336.41905.32121.58472_20336.41905.31747.22942_2',
]

want to get sort as an order like this

['20336.41905.32121.58472_20336.41905.60400.51092_1', '20336.41905.32121.58472_20336.41905.60400.48025_2', '20336.41905.32121.58472_20336.41905.31747.22942_2', '20336.41905.32121.58472_20336.41905.41816.60719_3', '20336.41905.32121.58472_20336.41905.41816.63631_4',

]

CodePudding user response:

We can try sorting using a lambda expression:

var arr = ['20336.41905.32121.58472_20336.41905.60400.51092_1',
    '20336.41905.32121.58472_20336.41905.60400.48025_2',
    '20336.41905.32121.58472_20336.41905.41816.60719_3',
    '20336.41905.32121.58472_20336.41905.41816.63631_4',
    '20336.41905.32121.58472_20336.41905.31747.22942_2',
];
arr.sort((a, b) => parseInt(a.split(/_(?!.*_)/)[1]) - parseInt(b.split(/_(?!.*_)/)[1]));
console.log(arr);

The logic used above is to split on the final underscore of each array value, and parse the right side number to an integer. Then we do a comparison of each pair of numbers to achieve the sort.

CodePudding user response:

Assuming you are using JavaScript...

The sort function can take a callback as an argument. You can use this to determine the criteria by which you desire to sort your array.

When comparing 2 values compare a to b, the function should return a number greater than zero if a goes after b, less than zero if a goes before b, and exactly zero if any could follow the other (ie. 1.10 and 1.100 could be sorted as [1.10, 1.00] or [1.100, 1.00] because for all we care they have the same value, on your particular case, 2 array elements ending in 4 would follow the same principle because that is the only number in our criteria).

An example would be:

arr.sort((a, b)=>{
    return parseInt(a.slice(-1)) - parseInt(b.slice(-1))
})

Note that this will only work if the last character on every element of your array is a numeric character and would not ever care about the second to last character if 2 last characters are equal.


There is an ugliest solution too that could work, although I don't really recommend it, it would take into consideration all characters in reverse order. Map over all elements, reverse them, sort the array without using a callback (arr.sort()), and then reverse all elements again.

  • Related