4 回答

TA贡献1874条经验 获得超12个赞
homes.sort( function(a, b) { if (a.city === b.city) { // Price is only important when cities are the same return b.price - a.price; } return a.city > b.city ? 1 : -1; });

TA贡献1848条经验 获得超2个赞
var homes = [ {"h_id":"3", "city":"Dallas", "state":"TX","zip":"75201","price":"162500"}, {"h_id":"4","city":"Bevery Hills", "state":"CA", "zip":"90210", "price":"319250"}, {"h_id":"6", "city":"Dallas", "state":"TX", "zip":"75000", "price":"556699"}, {"h_id":"5", "city":"New York", "state":"NY", "zip":"00010", "price":"962500"} ];homes.sort(fieldSorter(['city', '-price']));// homes.sort(fieldSorter(['zip', '-state', 'price'])); // alternativefunction fieldSorter(fields) { return function (a, b) { return fields .map(function (o) { var dir = 1; if (o[0] === '-') { dir = -1; o=o.substring(1); } if (a[o] > b[o]) return dir; if (a[o] < b[o]) return -(dir); return 0; }) .reduce(function firstNonZeroValue (p,n) { return p ? p : n; }, 0); };}
编辑:
"use strict";
const fieldSorter = (fields) => (a, b) => fields.map(o => {
let dir = 1;
if (o[0] === '-') { dir = -1; o=o.substring(1); }
return a[o] > b[o] ? dir : a[o] < b[o] ? -(dir) : 0;
}).reduce((p, n) => p ? p : n, 0);
const homes = [{"h_id":"3", "city":"Dallas", "state":"TX","zip":"75201","price":162500}, {"h_id":"4","city":"Bevery Hills", "state":"CA", "zip":"90210", "price":319250},{"h_id":"6", "city":"Dallas", "state":"TX", "zip":"75000", "price":556699},{"h_id":"5", "city":"New York", "state":"NY", "zip":"00010", "price":962500}];
const sortedHomes = homes.sort(fieldSorter(['state', '-price']));
document.write('<pre>' + JSON.stringify(sortedHomes, null, '\t') + '</pre>')
添加回答
举报