Javascript如何按字符串

时间:2018-06-11 08:34:47

标签: javascript sorting underscore.js collator

下面是我的对象数组的示例,我应该按名称对它们进行排序。 js正常排序按如下所示进行排序,但我的目标是按数值排序,例如:" 1 ex,2 ex,3 ex,4 ex,11 ex .."。有人可以帮我解决这个问题吗?

[{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"}]

5 个答案:

答案 0 :(得分:0)

    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)

答案 1 :(得分:0)

使用parseInt()拆分数字部分并将其转换为整数,然后您可以使用这些值对记录进行排序:



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);




答案 2 :(得分:0)

尝试以下

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);

答案 3 :(得分:0)

您必须在比较函数中包含解析函数,如下所示:

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

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

答案 4 :(得分:0)

@ user2004082 ,您也可以尝试使用以下代码获取相同内容。

  

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);

»输出

[ { 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' } ]