How to sort the last bit of an array

for example, an array:

[235, 42, 8, 100]

now you need to sort by last bit , and the final result should be:

[100, 42, 235, 8]

excuse me: how to achieve this function, what is needed is an algorithm

< hr >

Thank you for @ lejoy"s advice. A simple bubble last sort can be as follows:

function sort(arr) {
    for (let i = 0; i < arr.length; iPP) {
        for (let j = 1; j < arr.length; jPP) {
            // ...
            if (arr[j] % 10 < arr[j - 1] % 10) {
                let tmp = arr[j - 1]
                arr[j - 1] = arr[j]
                arr[j] = tmp
            }
        }
    }
    console.log(arr)
}
sort([55, 41, 32, 23, 19])
Mar.04,2021

is sorted in the same way as usual. For example, bubble sort: traverse and compare the two. The difference lies in: when comparing, both values of% 10 are modeled, the small ones are in the front and the large ones are in the back.


other languages arrange js as you like. If you don't use the built-in function, it's a pure algorithm.


choose one of the sorting categories of

if the last bit of mine is the same, there may be a problem. You can deal with it yourself, but the current data is OK

.
const arr = [235, 42, 8, 100]; // 
const map = {};
const lastArr = arr.map(i => {
    const str = i.toString();
    const strArr = [];
    for(let s of str) {
        strArr.push(s);
    };
    map[strArr[str.length - 1]] = i;
    return Number(strArr[str.length - 1]);
});
const newArr = [];
lastArr.sort().forEach(i => {
    if(i in map) {
        newArr.push(map[i])
    }
})
log(newArr) // [100, 42, 235, 8]
Menu