js对json数组进行排序
废话不多说,直接上代码
// 升序排列
function up(a, b) {
return a.val-b.val
},
// 降序排列
function down(a, b) {
return b.val-a.val
},
// sort 会直接对原数据排序
testJson.sort(up)
例如:
let test=[{"val":100},{"val":70},{"val":50},{"val":20},{"val":10}]
test=test.sort(up)
js根据json数组多个字段排序
let newArray = [
{product: "1", matno: "420200011480006",salebillno:"xsdd2733-8", sales: "800"},
{product: "2", matno: "420200011480007",salebillno:"xsdd2733-2", sales: "300"},
{product: "3", matno: "420200011480006",salebillno:"xsdd2733-5", sales: "100"},
{product: "4", matno: "420200011480006",salebillno:"xsdd2733-3", sales: "200"},
{product: "5", matno: "420200011480008",salebillno:"xsdd2738", sales: "600"},
{product: "6", matno: "420200011480010",salebillno:"xsdd2734", sales: "400"},
{product: "7", matno: "420200011480009",salebillno:"xsdd2735", sales: "700"},
{product: "8", matno: "420200011480001",salebillno:"xsdd2737", sales: "500"}
]
function sortByArr(arr, rev) {
if (rev == undefined) {
rev = 1;
} else {
rev = (rev) ? 1 : -1;
}
return function(a, b) {
for (var i = 0; i < arr.length; i++) {
let attr = arr[i]
if (a[attr] != b[attr]) {
if (a[attr] > b[attr]) {
return rev * 1;
} else {
return rev * -1;
}
}
}
}
}
newArray.sort(sortByArr(['matno','salebillno'],true))
[{product: '8', matno: '420200011480001', salebillno: 'xsdd2737', sales: '500'}
{product: '4', matno: '420200011480006', salebillno: 'xsdd2733-3', sales: '200'}
{product: '3', matno: '420200011480006', salebillno: 'xsdd2733-5', sales: '100'}
{product: '1', matno: '420200011480006', salebillno: 'xsdd2733-8', sales: '800'}
{product: '2', matno: '420200011480007', salebillno: 'xsdd2733-2', sales: '300'}
{product: '5', matno: '420200011480008', salebillno: 'xsdd2738', sales: '600'}
{product: '7', matno: '420200011480009', salebillno: 'xsdd2735', sales: '700'}
{product: '6', matno: '420200011480010', salebillno: 'xsdd2734', sales: '400'}]
newArray.sort(sortByArr(['matno'],false))
// 输出
[{product: '6', matno: '420200011480010', salebillno: 'xsdd2734', sales: '400'}
{product: '7', matno: '420200011480009', salebillno: 'xsdd2735', sales: '700'}
{product: '5', matno: '420200011480008', salebillno: 'xsdd2738', sales: '600'}
{product: '2', matno: '420200011480007', salebillno: 'xsdd2733-2', sales: '300'}
{product: '1', matno: '420200011480006', salebillno: 'xsdd2733-8', sales: '800'}
{product: '3', matno: '420200011480006', salebillno: 'xsdd2733-5', sales: '100'}
{product: '4', matno: '420200011480006', salebillno: 'xsdd2733-3', sales: '200'}
{product: '8', matno: '420200011480001', salebillno: 'xsdd2737', sales: '500'}]
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。