用数字排序数组

Sort array with numbers

这是我的数组:

var myArray = [
  '<@424507945156784498> - 152,800$',
  '<@381223410610501732> - 100$',
  '<@224451506344606852> - 74,424$',
  '<@101441124537903160> - 65,100$'
];

这就是我想要的:

var newArray = [
  '<@424507945156784498> - 152,800$',
  '<@224451506344606852> - 74,424$',
  '<@101441124537903160> - 65,100$'
  '<@381223410610501732> - 100$',      
];

我试过用这个方法 - Javascript : natural sort of alphanumerical strings 但它按 id (<@424507945156784498>) 排序,我如何按货币价值排序?

拆分和替换 - 排序将对现有数组进行排序 - 如果你不需要改变它,你需要将它复制到另一个数组:

var myArray = [
  '<@424507945156784498> - 152,800$',
  '<@381223410610501732> - 100$',
  '<@224451506344606852> - 74,424$',
  '<@101441124537903160> - 65,100$'
];
function toNum(str) {
  return +str.split(" - ")[1]  // get the amount
    .replace(/[^\d]/g,"");     // remove all non-numeric
}
myArray.sort(function(a,b) {
  return toNum(b)-toNum(a);    // numeric sort in situ
});
console.log(myArray)

使用 map-sort-map 成语:

  1. 将要排序的新数据映射到现有元素上
  2. 按添加的数据排序
  3. map 删除按
  4. 排序的元素

var myArray = [
  '<@424507945156784498> - 152,800$',
  '<@381223410610501732> - 100$',
  '<@224451506344606852> - 74,424$',
  '<@101441124537903160> - 65,100$'
];
    
console.log(
  myArray.map(e => [e, e.split(' - ')[1].replace(/[^0-9]/g,'')])
         .sort((a, b) => b[1] - a[1])
         .map(e => e[0])
);

试试下面的表达式:

myArray.sort((x,y)=>x.replace(/,/g,"").match(/(\d+)$/)[1]*1 < y.replace(/,/g,"").match(/(\d+)$/)[1]*1)

解释:

x.replace(/,/g,"").match(/(\d+)$/)[1]*1

此表达式删除逗号,然后匹配后跟 $ 的数字。这是针对排序方法中使用的 x 和 y 完成的。

var myArray = [
  '<@424507945156784498> - 152,800$',
  '<@381223410610501732> - 100$',
  '<@224451506344606852> - 74,424$',
  '<@101441124537903160> - 65,100$'
];

console.log(myArray.sort((x,y)=>x.replace(/,/g,"").match(/(\d+)$/)[1]*1 < y.replace(/,/g,"").match(/(\d+)$/)[1]*1))

简单地,提取价格值并按它排序:

var myArray = [
  '<@424507945156784498> - 152,800$',
  '<@381223410610501732> - 100$',
  '<@224451506344606852> - 74,424$',
  '<@101441124537903160> - 65,100$'
];

var result = myArray.sort((a,b) => {

  var [priceA, priceB] = [a,b].map(i => parseInt(i.split('-')[1].trim().replace(/\D/g,'')))

  return priceB - priceA;

});

console.log(result);