2017-08-18 56 views
0

我有一個像排序在Lodash排序依據轉換後的項目在不改變它

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?

(我將5050%數據,但顯示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這裏?

回答

2

你應該告訴ORDERBY通過item.COUNT做排序:

[item => parseInt(item.COUNT)], 

orderBy = _.orderBy; 
 

 
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.COUNT)], 
 
     ['desc'] 
 
    ); 
 
} else { 
 
    var orderByResults = orderBy(
 
     data, 
 
     prop, 
 
     order === 'descending' ? 'desc' : 'asc' 
 
    ); 
 
} 
 

 
console.log(orderByResults);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>