1233 javascript arrays sorting
我使用Ajax读取以下对象并将它们存储在一个数组中:
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": "5",
"city": "New York",
"state": "NY",
"zip": "00010",
"price": "962500"
}
];
Run Code Online (Sandbox Code Playgroud)
如何使用JavaScript 创建一个函数来按price
属性按升序 或 降序对对象进行排序?
Sto*_*bor 1571
按价格按升序排序房屋:
homes.sort(function(a, b) {
return parseFloat(a.price) - parseFloat(b.price);
});
Run Code Online (Sandbox Code Playgroud)
或者在ES6版本之后:
homes.sort((a, b) => parseFloat(a.price) - parseFloat(b.price));
Run Code Online (Sandbox Code Playgroud)
有些文档可以在这里找到.
Tri*_*ych 662
这是一个更灵活的版本,它允许您创建可重复使用的排序函数,并按任何字段排序.
const sort_by = (field, reverse, primer) => {
const key = primer ?
function(x) {
return primer(x[field])
} :
function(x) {
return x[field]
};
reverse = !reverse ? 1 : -1;
return function(a, b) {
return a = key(a), b = key(b), reverse * ((a > b) - (b > a));
}
}
//Now you can sort by any field at will...
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:"5",city:"New York",state:"NY",zip:"00010",price:"962500"}];
// Sort by price high to low
console.log(homes.sort(sort_by('price', true, parseInt)));
// Sort by city, case-insensitive, A-Z
console.log(homes.sort(sort_by('city', false, (a) => a.toUpperCase()
)));
Run Code Online (Sandbox Code Playgroud)
现在您可以随意按任意字段排序......
const sort_by = (field, reverse, primer) => {
const key = primer ?
function(x) {
return primer(x[field])
} :
function(x) {
return x[field]
};
reverse = !reverse ? 1 : -1;
return function(a, b) {
return a = key(a), b = key(b), reverse * ((a > b) - (b > a));
}
}
//Now you can sort by any field at will...
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:"5",city:"New York",state:"NY",zip:"00010",price:"962500"}];
// Sort by price high to low
console.log(homes.sort(sort_by('price', true, parseInt)));
// Sort by city, case-insensitive, A-Z
console.log(homes.sort(sort_by('city', false, (a) => a.toUpperCase()
)));
Run Code Online (Sandbox Code Playgroud)
Ric*_*mon 132
要对它进行排序,您需要创建一个带有两个参数的比较器函数.然后使用该比较器函数调用sort函数,如下所示:
// a and b are object elements of your array
function mycomparator(a,b) {
return parseInt(a.price, 10) - parseInt(b.price, 10);
}
homes.sort(mycomparator);
Run Code Online (Sandbox Code Playgroud)
如果要对升序进行排序,请在减号的每一侧切换表达式.
Ish*_*age 47
对于字符串排序,如果有人需要它,
const dataArr = {
"hello": [{
"id": 114,
"keyword": "zzzzzz",
"region": "Sri Lanka",
"supportGroup": "administrators",
"category": "Category2"
}, {
"id": 115,
"keyword": "aaaaa",
"region": "Japan",
"supportGroup": "developers",
"category": "Category2"
}]
};
const sortArray = dataArr['hello'];
console.log(sortArray.sort((a, b) => {
if (a.region < b.region)
return -1;
if (a.region > b.region)
return 1;
return 0;
}));
Run Code Online (Sandbox Code Playgroud)
Ste*_*uan 35
如果您有符合ES6标准的浏览器,则可以使用:
升序和降序排序顺序之间的差异是比较函数返回的值的符号:
var ascending = homes.sort((a, b) => Number(a.price) - Number(b.price));
var descending = homes.sort((a, b) => Number(b.price) - Number(a.price));
Run Code Online (Sandbox Code Playgroud)
这是一个有效的代码片段:
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": "5",
"city": "New York",
"state": "NY",
"zip": "00010",
"price": "962500"
}];
homes.sort((a, b) => Number(a.price) - Number(b.price));
console.log("ascending", homes);
homes.sort((a, b) => Number(b.price) - Number(a.price));
console.log("descending", homes);
Run Code Online (Sandbox Code Playgroud)
Tim*_*ert 22
你想用Javascript对它进行排序,对吧?你想要的是sort()
功能.在这种情况下,您需要编写一个比较器函数并将其传递给sort()
,如下所示:
function comparator(a, b) {
return parseInt(a["price"], 10) - parseInt(b["price"], 10);
}
var json = { "homes": [ /* your previous data */ ] };
console.log(json["homes"].sort(comparator));
Run Code Online (Sandbox Code Playgroud)
比较器从阵列中的每个嵌套哈希中取出一个,并通过检查"price"字段来决定哪一个更高.
jhe*_*rax 21
我推荐GitHub:Array sortBy - sortBy
使用Schwartzian变换的方法的最佳实现
但是现在我们将尝试这种方法Gist:sortBy-old.js.
让我们创建一个方法来排序能够通过某些属性排列对象的数组.
var sortBy = (function () {
var toString = Object.prototype.toString,
// default parser function
parse = function (x) { return x; },
// gets the item to be sorted
getItem = function (x) {
var isObject = x != null && typeof x === "object";
var isProp = isObject && this.prop in x;
return this.parser(isProp ? x[this.prop] : x);
};
/**
* Sorts an array of elements.
*
* @param {Array} array: the collection to sort
* @param {Object} cfg: the configuration options
* @property {String} cfg.prop: property name (if it is an Array of objects)
* @property {Boolean} cfg.desc: determines whether the sort is descending
* @property {Function} cfg.parser: function to parse the items to expected type
* @return {Array}
*/
return function sortby (array, cfg) {
if (!(array instanceof Array && array.length)) return [];
if (toString.call(cfg) !== "[object Object]") cfg = {};
if (typeof cfg.parser !== "function") cfg.parser = parse;
cfg.desc = !!cfg.desc ? -1 : 1;
return array.sort(function (a, b) {
a = getItem.call(cfg, a);
b = getItem.call(cfg, b);
return cfg.desc * (a < b ? -1 : +(a > b));
});
};
}());
Run Code Online (Sandbox Code Playgroud)
var data = [
{date: "2011-11-14T16:30:43Z", quantity: 2, total: 90, tip: 0, type: "tab"},
{date: "2011-11-14T17:22:59Z", quantity: 2, total: 90, tip: 0, type: "Tab"},
{date: "2011-11-14T16:28:54Z", quantity: 1, total: 300, tip: 200, type: "visa"},
{date: "2011-11-14T16:53:41Z", quantity: 2, total: 90, tip: 0, type: "tab"},
{date: "2011-11-14T16:48:46Z", quantity: 2, total: 90, tip: 0, type: "tab"},
{date: "2011-11-14T17:25:45Z", quantity: 2, total: 200, tip: 0, type: "cash"},
{date: "2011-11-31T17:29:52Z", quantity: 1, total: 200, tip: 100, type: "Visa"},
{date: "2011-11-14T16:58:03Z", quantity: 2, total: 90, tip: 0, type: "tab"},
{date: "2011-11-14T16:20:19Z", quantity: 2, total: 190, tip: 100, type: "tab"},
{date: "2011-11-01T16:17:54Z", quantity: 2, total: 190, tip: 100, type: "tab"},
{date: "2011-11-14T17:07:21Z", quantity: 2, total: 90, tip: 0, type: "tab"},
{date: "2011-11-14T16:54:06Z", quantity: 1, total: 100, tip: 0, type: "Cash"}
];
Run Code Online (Sandbox Code Playgroud)
安排所述阵列,通过"date"
如String
// sort by @date (ascending)
sortBy(data, { prop: "date" });
// expected: first element
// { date: "2011-11-01T16:17:54Z", quantity: 2, total: 190, tip: 100, type: "tab" }
// expected: last element
// { date: "2011-11-31T17:29:52Z", quantity: 1, total: 200, tip: 100, type: "Visa"}
Run Code Online (Sandbox Code Playgroud)
如果要忽略区分大小写,请设置parser
回调:
// sort by @type (ascending) IGNORING case-sensitive
sortBy(data, {
prop: "type",
parser: (t) => t.toUpperCase()
});
// expected: first element
// { date: "2011-11-14T16:54:06Z", quantity: 1, total: 100, tip: 0, type: "Cash" }
// expected: last element
// { date: "2011-11-31T17:29:52Z", quantity: 1, total: 200, tip: 100, type: "Visa" }
Run Code Online (Sandbox Code Playgroud)
如果要将"date"
字段转换为Date
类型:
// sort by @date (descending) AS Date object
sortBy(data, {
prop: "date",
desc: true,
parser: (d) => new Date(d)
});
// expected: first element
// { date: "2011-11-31T17:29:52Z", quantity: 1, total: 200, tip: 100, type: "Visa"}
// expected: last element
// { date: "2011-11-01T16:17:54Z", quantity: 2, total: 190, tip: 100, type: "tab" }
Run Code Online (Sandbox Code Playgroud)
在这里你可以玩代码: jsbin.com/lesebi
感谢@Ozesh的反馈意见,修复了与具有假值的属性相关的问题.
Eva*_*oll 16
使用lodash.sortBy,(使用commonjs的说明,你也可以在你的html顶部放置cdn的脚本include-tag)
var sortBy = require('lodash.sortby');
// or
sortBy = require('lodash').sortBy;
Run Code Online (Sandbox Code Playgroud)
降序排列
var descendingOrder = sortBy( homes, 'price' ).reverse();
Run Code Online (Sandbox Code Playgroud)
升序
var ascendingOrder = sortBy( homes, 'price' );
Run Code Online (Sandbox Code Playgroud)
虽然我知道 OP 想要对数字数组进行排序,但此问题已被标记为有关字符串的类似问题的答案。为此,上述答案没有考虑对大小写很重要的文本数组进行排序。大多数答案采用字符串值并将它们转换为大写/小写,然后以一种或另一种方式排序。我遵守的要求很简单:
我期望的是,[ A, a, B, b, C, c ]
但上面的答案返回A, B, C, a, b, c
。实际上,我在这个问题上挠头的时间比我想要的要长(这就是我发布此内容的原因,希望它至少能帮助另一个人)。虽然有两个用户localeCompare
在标记答案的评论中提到了该功能,但直到我在四处搜索时偶然发现该功能后,我才看到这一点。在阅读了 String.prototype.localeCompare() 文档后,我想出了这个:
var values = [ "Delta", "charlie", "delta", "Charlie", "Bravo", "alpha", "Alpha", "bravo" ];
var sorted = values.sort((a, b) => a.localeCompare(b, undefined, { caseFirst: "upper" }));
// Result: [ "Alpha", "alpha", "Bravo", "bravo", "Charlie", "charlie", "Delta", "delta" ]
Run Code Online (Sandbox Code Playgroud)
这告诉函数在小写值之前对大写值进行排序。localeCompare
函数中的第二个参数是定义语言环境,但如果您保留它,undefined
它会自动为您计算语言环境。
这也适用于对对象数组进行排序:
var values = [
{ id: 6, title: "Delta" },
{ id: 2, title: "charlie" },
{ id: 3, title: "delta" },
{ id: 1, title: "Charlie" },
{ id: 8, title: "Bravo" },
{ id: 5, title: "alpha" },
{ id: 4, title: "Alpha" },
{ id: 7, title: "bravo" }
];
var sorted = values
.sort((a, b) => a.title.localeCompare(b.title, undefined, { caseFirst: "upper" }));
Run Code Online (Sandbox Code Playgroud)
这可以通过简单的一行valueof()排序函数来实现.在下面运行代码片段以查看演示.
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": "5",
"city": "New York",
"state": "NY",
"zip": "00010",
"price": "962500"
}
];
console.log("To sort descending/highest first, use operator '<'");
homes.sort(function(a,b) { return a.price.valueOf() < b.price.valueOf();});
console.log(homes);
console.log("To sort ascending/lowest first, use operator '>'");
homes.sort(function(a,b) { return a.price.valueOf() > b.price.valueOf();});
console.log(homes);
Run Code Online (Sandbox Code Playgroud)
价格降序:
homes.sort((x,y) => {return y.price - x.price})
Run Code Online (Sandbox Code Playgroud)
价格升序:
homes.sort((x,y) => {return x.price - y.price})
Run Code Online (Sandbox Code Playgroud)
这是上述所有答案的高潮。
小提琴验证:http : //jsfiddle.net/bobberino/4qqk3/
var sortOn = function (arr, prop, reverse, numeric) {
// Ensure there's a property
if (!prop || !arr) {
return arr
}
// Set up sort function
var sort_by = function (field, rev, primer) {
// Return the required a,b function
return function (a, b) {
// Reset a, b to the field
a = primer(a[field]), b = primer(b[field]);
// Do actual sorting, reverse as needed
return ((a < b) ? -1 : ((a > b) ? 1 : 0)) * (rev ? -1 : 1);
}
}
// Distinguish between numeric and string to prevent 100's from coming before smaller
// e.g.
// 1
// 20
// 3
// 4000
// 50
if (numeric) {
// Do sort "in place" with sort_by function
arr.sort(sort_by(prop, reverse, function (a) {
// - Force value to a string.
// - Replace any non numeric characters.
// - Parse as float to allow 0.02 values.
return parseFloat(String(a).replace(/[^0-9.-]+/g, ''));
}));
} else {
// Do sort "in place" with sort_by function
arr.sort(sort_by(prop, reverse, function (a) {
// - Force value to string.
return String(a).toUpperCase();
}));
}
}
Run Code Online (Sandbox Code Playgroud)
我参加聚会的时间不晚,但下面是我排序的逻辑。
function getSortedData(data, prop, isAsc) {
return data.sort((a, b) => {
return (a[prop] < b[prop] ? -1 : 1) * (isAsc ? 1 : -1)
});
}
Run Code Online (Sandbox Code Playgroud)
您可以使用 string1.localeCompare(string2) 进行字符串比较
this.myArray.sort((a,b) => {
return a.stringProp.localeCompare(b.stringProp);
});
Run Code Online (Sandbox Code Playgroud)
请注意,localCompare
是区分在敏感
一个更像 LINQ 的解决方案:
Array.prototype.orderBy = function (selector, desc = false) {
return [...this].sort((a, b) => {
a = selector(a);
b = selector(b);
if (a == b) return 0;
return (desc ? a > b : a < b) ? -1 : 1;
});
}
Run Code Online (Sandbox Code Playgroud)
优点:
用法:
Array.prototype.orderBy = function(selector, desc = false) {
return [...this].sort((a, b) => {
a = selector(a);
b = selector(b);
if (a == b) return 0;
return (desc ? a > b : a < b) ? -1 : 1;
});
};
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": "5",
"city": "New York",
"state": "NY",
"zip": "00010",
"price": "962500"
}];
let sorted_homes = homes.orderBy(h => parseFloat(h.price));
console.log("sorted by price", sorted_homes);
let sorted_homes_desc = homes.orderBy(h => h.city, true);
console.log("sorted by City descending", sorted_homes_desc);
Run Code Online (Sandbox Code Playgroud)
您可以使用sort
带有回调函数的 JavaScript方法:
function compareASC(homeA, homeB)
{
return parseFloat(homeA.price) - parseFloat(homeB.price);
}
function compareDESC(homeA, homeB)
{
return parseFloat(homeB.price) - parseFloat(homeA.price);
}
// Sort ASC
homes.sort(compareASC);
// Sort DESC
homes.sort(compareDESC);
Run Code Online (Sandbox Code Playgroud)
要对数组进行排序,您必须定义一个比较器函数。此功能在您想要的排序模式或顺序(即升序或降序)上总是不同的。
让我们创建一些函数,对数组进行升序或降序排序,并包含对象、字符串或数值。
function sorterAscending(a,b) {
return a-b;
}
function sorterDescending(a,b) {
return b-a;
}
function sorterPriceAsc(a,b) {
return parseInt(a['price']) - parseInt(b['price']);
}
function sorterPriceDes(a,b) {
return parseInt(b['price']) - parseInt(b['price']);
}
Run Code Online (Sandbox Code Playgroud)
对数字进行排序(按字母顺序和升序):
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
Run Code Online (Sandbox Code Playgroud)
对数字进行排序(按字母顺序和降序):
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
fruits.reverse();
Run Code Online (Sandbox Code Playgroud)
排序数字(数字和升序):
var points = [40,100,1,5,25,10];
points.sort(sorterAscending());
Run Code Online (Sandbox Code Playgroud)
排序数字(数字和降序):
var points = [40,100,1,5,25,10];
points.sort(sorterDescending());
Run Code Online (Sandbox Code Playgroud)
如上所述,将 sorterPriceAsc 和 sorterPriceDes 方法与具有所需键的数组一起使用。
homes.sort(sorterPriceAsc()) or homes.sort(sorterPriceDes())
Run Code Online (Sandbox Code Playgroud)
我还使用了某种评级和多个字段排序:
arr = [
{type:'C', note:834},
{type:'D', note:732},
{type:'D', note:008},
{type:'F', note:474},
{type:'P', note:283},
{type:'P', note:165},
{type:'X', note:173},
{type:'Z', note:239},
];
arr.sort(function(a,b){
var _a = ((a.type==='C')?'0':(a.type==='P')?'1':'2');
_a += (a.type.localeCompare(b.type)===-1)?'0':'1';
_a += (a.note>b.note)?'1':'0';
var _b = ((b.type==='C')?'0':(b.type==='P')?'1':'2');
_b += (b.type.localeCompare(a.type)===-1)?'0':'1';
_b += (b.note>a.note)?'1':'0';
return parseInt(_a) - parseInt(_b);
});
Run Code Online (Sandbox Code Playgroud)
结果
[
{"type":"C","note":834},
{"type":"P","note":165},
{"type":"P","note":283},
{"type":"D","note":8},
{"type":"D","note":732},
{"type":"F","note":474},
{"type":"X","note":173},
{"type":"Z","note":239}
]
Run Code Online (Sandbox Code Playgroud)
虽然仅对单个数组进行排序有点矫枉过正,但此原型函数允许使用语法按任何键(包括嵌套键)按任何键(包括嵌套键)对 Javascript 数组进行排序dot
。
(function(){
var keyPaths = [];
var saveKeyPath = function(path) {
keyPaths.push({
sign: (path[0] === '+' || path[0] === '-')? parseInt(path.shift()+1) : 1,
path: path
});
};
var valueOf = function(object, path) {
var ptr = object;
for (var i=0,l=path.length; i<l; i++) ptr = ptr[path[i]];
return ptr;
};
var comparer = function(a, b) {
for (var i = 0, l = keyPaths.length; i < l; i++) {
aVal = valueOf(a, keyPaths[i].path);
bVal = valueOf(b, keyPaths[i].path);
if (aVal > bVal) return keyPaths[i].sign;
if (aVal < bVal) return -keyPaths[i].sign;
}
return 0;
};
Array.prototype.sortBy = function() {
keyPaths = [];
for (var i=0,l=arguments.length; i<l; i++) {
switch (typeof(arguments[i])) {
case "object": saveKeyPath(arguments[i]); break;
case "string": saveKeyPath(arguments[i].match(/[+-]|[^.]+/g)); break;
}
}
return this.sort(comparer);
};
})();
Run Code Online (Sandbox Code Playgroud)
用法:
var data = [
{ name: { first: 'Josh', last: 'Jones' }, age: 30 },
{ name: { first: 'Carlos', last: 'Jacques' }, age: 19 },
{ name: { first: 'Carlos', last: 'Dante' }, age: 23 },
{ name: { first: 'Tim', last: 'Marley' }, age: 9 },
{ name: { first: 'Courtney', last: 'Smith' }, age: 27 },
{ name: { first: 'Bob', last: 'Smith' }, age: 30 }
]
data.sortBy('age'); // "Tim Marley(9)", "Carlos Jacques(19)", "Carlos Dante(23)", "Courtney Smith(27)", "Josh Jones(30)", "Bob Smith(30)"
Run Code Online (Sandbox Code Playgroud)
使用点语法或数组语法按嵌套属性排序:
data.sortBy('name.first'); // "Bob Smith(30)", "Carlos Dante(23)", "Carlos Jacques(19)", "Courtney Smith(27)", "Josh Jones(30)", "Tim Marley(9)"
data.sortBy(['name', 'first']); // "Bob Smith(30)", "Carlos Dante(23)", "Carlos Jacques(19)", "Courtney Smith(27)", "Josh Jones(30)", "Tim Marley(9)"
Run Code Online (Sandbox Code Playgroud)
按多个键排序:
data.sortBy('name.first', 'age'); // "Bob Smith(30)", "Carlos Jacques(19)", "Carlos Dante(23)", "Courtney Smith(27)", "Josh Jones(30)", "Tim Marley(9)"
data.sortBy('name.first', '-age'); // "Bob Smith(30)", "Carlos Dante(23)", "Carlos Jacques(19)", "Courtney Smith(27)", "Josh Jones(30)", "Tim Marley(9)"
Run Code Online (Sandbox Code Playgroud)
你可以分叉 repo:https : //github.com/eneko/Array.sortBy
使用 ECMAScript 6 StoBor 的答案可以做得更简洁:
homes.sort((a, b) => a.price - b.price)
Run Code Online (Sandbox Code Playgroud)