如何通过数字参数对对象数组进行排序?

时间:2022-07-21 16:02:04

I have an array of objects:

我有一个对象数组:

var arr = [{"name":"first", value:"170"},
{"name":"second", value:"150"},
{"name":"second", value:"250"}]

How can I sort it by value?

我怎样才能按价值排序?

1 个解决方案

#1


2  

You could use Array#sort with a callback for the values.

您可以使用Array#sort和值的回调。

var arr = [{ "name": "first", value: "170" }, { "name": "second", value: "150" }, { "name": "second", value: "250" }];

arr.sort(function (a, b) {
    return a.value - b.value;
});

console.log(arr);

#1


2  

You could use Array#sort with a callback for the values.

您可以使用Array#sort和值的回调。

var arr = [{ "name": "first", value: "170" }, { "name": "second", value: "150" }, { "name": "second", value: "250" }];

arr.sort(function (a, b) {
    return a.value - b.value;
});

console.log(arr);