我希望能够根据字符串中的第一个单词在JavaScript中对数组中的对象数组进行排序。目前我正在使用的排序函数使用字符串中的所有单词。
JSON数据:
"awds": [
{"awd":"adobe edge award"},
{"awd":"besty"},
{"awd":"c award"},
{"awd":"awwward award"},
{"awd":"desk award"},
{"awd":"adobe edge award"},
{"awd":"creative edge award"},
{"awd":"snoogle edge award"},
{"awd":"scuba edge award"},
{"awd":"xidoe edge award"}
]
JavaScript的:
var compareNames = function(a, b) {
var nameA = a.awd.toLowerCase();
var nameB = b.awd.toLowerCase();
if (nameA > nameB) { return 1; }
return 0;
};
当前输出:
adobe edge award
besty
c award
awwward award
desk award
adobe edge award
creative edge award
snoogle edge award
scuba edge award
xidoe edge award
期望的输出:
adobe edge award
adobe edge award
awwward award
c award
creative edge award
scuba edge award
snoogle edge award
xidoe edge award
答案 0 :(得分:1)
您可以将Array.sort
与比较功能结合使用。见https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/sort
答案 1 :(得分:1)
awds.sort(function (a, b) {
var aword = a.awd.toLowerCase().match(/[^ ]+/)[0];
var bword = b.awd.toLowerCase().match(/[^ ]+/)[0];
return aword == bword ? 0 : (aword < bword ? -1 : 1);
});
答案 2 :(得分:1)
var o = [
{"awd":"adobe edge award"},
{"awd":"besty"},
{"awd":"c award"},
{"awd":"awwward award"},
{"awd":"desk award"},
{"awd":"adobe edge award"},
{"awd":"creative edge award"},
{"awd":"snoogle edge award"},
{"awd":"scuba edge award"},
{"awd":"xidoe edge award"}
];
o.sort(function(a, b) {
var nameA = a.awd.toLowerCase();
var nameB = b.awd.toLowerCase();
if(nameA === nameB) return 0;
return nameA > nameB ? 1 : -1;
});
console.log(o);
答案 3 :(得分:0)
如果在第一项不大于第二项时返回-1,则您的方法将起作用 -
var compareNames = function(a, b) {
var nameA = a.awd.toLowerCase();
var nameB = b.awd.toLowerCase();
if(nameA==nameB) return 0;
return (nameA > nameB)? 1:-1;
};