我有一个字符串数组,我需要根据每个字符串中的前4个数字对这些字符串进行排序。但是,如何针对这些数字进行排序?代码工作正常,我只需要对其进行排序。
我已经尝试过.substring,但是我认为这不是正确的方法。
var volunteers = [ '9.05', '16.29', '26.67', '0.00', '2.25' ]
getResults: function(volunteers) {
this.results = [];
for (var i = 0; i < volunteers.length; i++) {
var dayNames = this.data[i][3] || " ";
var result = (volunteers[i] + " additional volunteers are needed on day " + i +" " +dayNames);
this.results.push(result);
}
console.log(this.results)
return this.results;
}
//Expected
[ '26.67 additional volunteers are needed on day 2 Tuesday',
'16.29 additional volunteers are needed on day 1 Monday',
'9.05 additional volunteers are needed on day 0 Sunday',
'2.25 additional volunteers are needed on day 4 ',
'0.00 additional volunteers are needed on day 3 Wednesday' ]
//Actual
[ '9.05 additional volunteers are needed on day 0 Sunday',
'16.29 additional volunteers are needed on day 1 Monday',
'26.67 additional volunteers are needed on day 2 Tuesday',
'0.00 additional volunteers are needed on day 3 Wednesday',
'2.25 additional volunteers are needed on day 4 ' ]
答案 0 :(得分:0)
先排序:
SQL group by
答案 1 :(得分:0)
您可以获取索引并按降序对它们进行排序,并使用排序后的索引映射字符串。
var volunteers = ['9.05', '16.29', '26.67', '0.00', '2.25'],
days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
result = [...volunteers.keys()]
.sort((a, b) => volunteers[b] - volunteers[a])
.map(i => `${volunteers[i]} additional volunteers are needed on day ${i} ${days[i]}`);
console.log(result);
答案 2 :(得分:0)
var volunteers = [ '9.05', '16.29', '26.67', '0.00', '2.25' ];
var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
this.results = [];
for (var i = 0; i < volunteers.length; i++) {
var result = {
'value':volunteers[i] ,
'name' : volunteers[i] + " additional volunteers are needed on day " + i +" " +days[i]
}
this.results.push(result);
}
this.results.sort(function(a, b) {
return a.value - b.value;
}).reverse();
var result = this.results.map(a => a.name);
console.log(result);
答案 3 :(得分:0)
尝试一下:
function getNumber(string) {
const numbers = string.match(/[0-9\.]+/g)[0] || 0
return Number(numbers);
}
function sort (volunteers) {
return volunteers.sort((a, b) => getNumber(a) - getNumber(b));
}
sort(volunteers)
答案 4 :(得分:0)
parseFloat
可用于获取数字部分:
var arr = [ '9.05 additional volunteers are needed on day 0 Sunday',
'16.29 additional volunteers are needed on day 1 Monday',
'26.67 additional volunteers are needed on day 2 Tuesday',
'0.00 additional volunteers are needed on day 3 Wednesday',
'2.25 additional volunteers are needed on day 4' ]
console.log( arr.sort((a, b) => parseFloat(b) - parseFloat(a)) )