0
let data = [
{DATE: "2017-08-18", COUNT: "65", EVENT_NAME: "TAX_EXEMPTION_FAILURE"},
{DATE: "2017-08-18", COUNT: "63", EVENT_NAME: "FRAUD_NOT_DONE"},
{DATE: "2017-08-18", COUNT: "4451", EVENT_NAME: "FRAUD_ACCEPT"},
];
我想的COUNT
的數值進行排序,像65, 63, 4451
數據,數字和不是字符串。因爲它被顯示在它的格式的表格,我不能改變數據基於Lodash : how to do a case insensitive sorting on a collection using orderBy?
(我將50
50%
數據,但顯示50%
等排序),我在[item => parseInt(item)]
傳遞給orderBy
。
下面的腳本不工作:
const _ = require("lodash");
const orderBy = require('lodash/orderBy');
// import some from 'lodash/some';
function isNumber(item) {
let isnum = /^\d+$/.test(item);
return isnum;
}
function are_all_numbers(data, key) {
let values = _.map(data, key);
return _.every(values, isNumber);
}
let data = [
{DATE: "2017-08-18", COUNT: "65", EVENT_NAME: "TAX_EXEMPTION_FAILURE"},
{DATE: "2017-08-18", COUNT: "63", EVENT_NAME: "FRAUD_NOT_DONE"},
{DATE: "2017-08-18", COUNT: "4451", EVENT_NAME: "FRAUD_ACCEPT"},
];
let order = 'descending';
let all_are_numbers = are_all_numbers(data, 'COUNT');
console.log('all_are_numbers:');
console.log(all_are_numbers);
if (all_are_numbers) {
var orderByResults = orderBy(
data,
[item => parseInt(item)],
['desc']
);
} else {
var orderByResults = orderBy(
data,
prop,
order === 'descending' ? 'desc' : 'asc'
);
}
console.log(orderByResults);
它運行:
$ node test_script.js
all_are_numbers:
true
[ { DATE: '2017-08-18',
COUNT: '65',
EVENT_NAME: 'TAX_EXEMPTION_FAILURE' },
{ DATE: '2017-08-18', COUNT: '63', EVENT_NAME: 'FRAUD_NOT_DONE' },
{ DATE: '2017-08-18', COUNT: '4451', EVENT_NAME: 'FRAUD_ACCEPT' } ]
爲什麼沒有排序由parseInt
這裏?