我有一个带有键值对的数组,数组列是id和name。我想按ID对这个数组排序。
id列的值是字符串类型,但我想将它们排序为数字值。
var items = [
{
"id": "165",
"name": "a"
},
{
"id": "236",
"name": "c"
},
{
"id": "376",
"name": "b"
},
{
"id": "253",
"name": "f"
},
{
"id": "235",
"name": "e"
},
{
"id": "24",
"name": "d"
},
{
"id": "26",
"name": "d"
}
]
答案 0 :(得分:3)
items.sort((a,b)=>a.id-b.id)
答案 1 :(得分:1)
使用Arrays.sort()
var arr = [{"id":"165","name":"a"},{"id":"236","name":"c"},{"id":"376","name":"b"},{"id":"253","name":"f"},{"id":"235","name":"e"},{"id":"24","name":"d"},{"id":"26","name":"d"}];
arr.sort((a,b)=> Number(a.id) - Number(b.id));
console.log(arr);
答案 2 :(得分:1)
for (int[] arr : allNumList) {
for (int i : arr) {
if (i == numb) {
return false;
}
}
}
答案 3 :(得分:1)
<button type="button" id="editArticleButton" class="btn btn-info btn-block" data-toggle="modal" data-target="#modalEditArticle"><span class="glyphicon glyphicon-edit"></span> Edit </button>
答案 4 :(得分:0)
可以通过多种方式比较数字字符串。假设字符串为a
和b
,
a-b
parseInt(a) - parseInt(b)
-参考-Java Script parseInt +a - +b
-参考-Unary +
operator to convert string to number Number(a) - Number(b)
-参考-Javascript Global Number Object
var items = [{"id": "165","name": "a"},{"id": "236","name": "c"},{"id": "376","name": "b"},{"id": "253","name": "f"},{"id": "235","name": "e"},{"id": "24","name": "d"},{"id": "26","name": "d"}];
console.log(items.sort(function(a,b){ return parseInt(a.id)-parseInt(b.id) }));
console.log(items.sort(function(a,b){ return a.id-b.id }));
console.log(items.sort(function(a,b){ return +a.id - +b.id }));
console.log(items.sort(function(a,b){ return Number(a.id)-Number(b.id) }));