简体   繁体   中英

Sorting Javascript Array with Split Function

I have an array that looks like this

var testArray = ['name1:13', 'name2:15', 'name3:13'];

I would like to sort the array by the number to the right of the colon.

So far I have this:

var converted = testArray.map(
            function (item) {
                return item.split(':').map(
            function (num) {
                return parseInt(num);
          });
        })

        alert(converted)
        var sorted = converted.sort(function (a, b) { return a[1] - b[1] })
        alert(sorted);

That sorts them in the correct order but I'm not sure how to pass over the first part of each string, the part to the left of the colon.

Right now it returns: NAN,13,NAN,13,NAN,15

Make a helper function to access the [1] st index of the split result, then in the sort callback, call that function for both and return the difference:

 var testArray = ['name1:13', 'name2:15', 'name3:13']; const getVal = str => str.split(':')[1]; testArray.sort((a, b) => getVal(a) - getVal(b)); console.log(testArray);

Split, convert to number and compare.

 var testArray = ["name1:13", "name2:15", "name3:13"]; const sortFunction = (a, b) => { const value = str => Number(str.split(":")[1]); return value(a) - value(b); }; testArray.sort(sortFunction); console.log(testArray);

 var testArray = ['name1:13', 'name2:15', 'name3:13']; console.log(testArray.sort((a, b) => (a.split(":")[1] > b.split(":")[1]) ? 1 : -1))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM