使用引号在javascript中对数组进行排序

时间:2017-08-16 05:59:01

标签: javascript arrays sorting

我有一个数组

var arr = ['hello','"end" two', 'end one', 'yes', 'abc' ];

我需要按如下所示对其进行排序

// abc,  end one, "end" two, hello, yes

我该怎么办?

4 个答案:

答案 0 :(得分:5)

您可以使用String#localeCompare's option进行排序。

  

<强> ignorePunctuation

     

是否应忽略标点符号。可能的值为truefalse;默认值为false

&#13;
&#13;
var array = ['hello', '"end" two', 'end one', 'yes', 'abc'];

array.sort(function (a, b) {
    return a.localeCompare(b, undefined, { ignorePunctuation: true });
});

console.log(array);
&#13;
&#13;
&#13;

答案 1 :(得分:2)

&#13;
&#13;
function sortarray(a,b) {
  a = a.replace(/"/g,'');
  b = b.replace(/"/g,'');

    return (a < b ? -1 : 1);
}

keys = ['hello','"end" two', 'end one', 'yes', 'abc' ]

var sorted = keys.sort(sortarray);
alert(sorted);
&#13;
&#13;
&#13;

这是创建的功能,可以直接在你想要的地方使用。

答案 2 :(得分:1)

function sortarray(one,two) {
  one = one.replace(/"/g,'');
  two = two.replace(/"/g,'');

    return (one < two ? -1 : 1);
}

keys = ['hello','"end" two', 'end one', 'yes', 'abc' ]

var sorted = keys.sort(sortarray);
alert(sorted);

答案 3 :(得分:0)

接受的答案是删除每个比较的引号,如果有很多项,这可能是一个问题。而是创建一个并行的值数组,用于排序:

const sortValues = arr.map(elt => elt.replace(/"/g, ''));

现在根据这些值对从0开始的数字列表进行排序:

const sortIndexes = arr.map((_, i) => i)
  .sort((a, b) => sortValues[a].localeCompare(sortValues[b]));

然后根据排序的索引重新排序输入数组:

const result = sortIndexes.map(i => arr[i]);