Javascript how to sort array of objects by numeric value of the string [duplicate]

China☆狼群 提交于 2020-06-23 09:45:38

问题


Below is an example of my array of objects and I am supposed to sort these by name. The js normal sorting sorts as shown below, however my target is to sort by the numeric value, eg: "1 ex, 2 ex, 3 ex, 4 ex, 11 ex ..". Could someone help me how to achieve this?

[{id: 588, name: "1 ex"}
{id: 592, name: "11 ex"}
{id: 607, name: "2 ex"}
{id: 580, name: "3 ex"}
{id: 596, name: "4 ex"}]

回答1:


You have to include the parse function in your compare function like this:

var compare = function(a, b) {
  return parseInt(a.name) - parseInt(b.name);
}

console.log(x.sort(compare));



回答2:


    arr = [{id: 588, name: "1 ex"},
    {id: 592, name: "11 ex"},
    {id: 607, name: "2 ex"},
    {id: 580, name: "3 ex"},
    {id: 596, name: "4 ex"}]
    
    result = arr.sort(function(a, b) { return parseInt(a.name) > parseInt(b.name) })
    console.log(result)



回答3:


Split and convert the numeric part to integer using parseInt() then you can use those values to sort the records:

var arr = [{id: 588, name: "1 ex"},
{id: 592, name: "11 ex"},
{id: 607, name: "2 ex"},
{id: 580, name: "3 ex"},
{id: 596, name: "4 ex"}];

arr.sort(function (a, b) {
  var aNum = parseInt(a.name);
  var bNum = parseInt(b.name);
  return aNum - bNum;
});

console.log(arr);



回答4:


Try following

let arr = [{id: 588, name: "1 ex"},
{id: 592, name: "11 ex"},
{id: 607, name: "2 ex"},
{id: 580, name: "3 ex"},
{id: 596, name: "4 ex"}];

arr.sort((a,b) => a.name.split(" ")[0] - b.name.split(" ")[0]);

console.log(arr);



回答5:


@user2004082, you can also try the below code to get the same as you want.

Try it online at http://rextester.com/GUPBC15345.

var arr = [{id: 588, name: "1 ex"},
{id: 592, name: "11 ex"},
{id: 607, name: "2 ex"},
{id: 580, name: "3 ex"},
{id: 596, name: "4 ex"}];

var map = {}
for(var item of arr) {
    map[item["name"]] = item;   
}

var arr = arr.map(function(item){return item["name"]}).sort(function(a, b){
    var a = parseInt(a.split(' ')[0]);
    var b = parseInt(b.split(' ')[0]);

    return a-b;
}).map(function(name){
    return map[name];
})

console.log(arr);

» Output

[ { id: 588, name: '1 ex' },
  { id: 607, name: '2 ex' },
  { id: 580, name: '3 ex' },
  { id: 596, name: '4 ex' },
  { id: 592, name: '11 ex' } ]


来源:https://stackoverflow.com/questions/50793491/javascript-how-to-sort-array-of-objects-by-numeric-value-of-the-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!