简体   繁体   English

使用拆分函数对 Javascript 数组进行排序

[英]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现在它返回: 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:创建一个辅助函数来访问拆分结果的[1] st 索引,然后在排序回调中,为两者调用该函数并返回差值:

 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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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