【问题标题】:Sorting in javascript [duplicate]在javascript中排序[重复]
【发布时间】:2013-07-31 21:26:48
【问题描述】:

这是我想要排序的数组的示例。

    [ { nums: 'http://s3.amazonaws.com/1375304393109.png',
        variant: { name: 'original' } },
      { nums: 'http://s3.amazonaws.com/2315456487896.jpg',
        variant: { name: 'original' } },
      { nums: 'http://s3.amazonaws.com/1375304393109.png',
        variant: { name: 'r256x200', size: '256x200' } },
      { nums: 'http://s3.amazonaws.com/1375304393091.jpg',
        variant: { name: 'r256x200', size: '256x200' } },
      { nums: 'http://s3.amazonaws.com/2315456487896.jpg',
        variant: { name: 'r512x400', size: '512x400' } },
      { nums: 'http://s3.amazonaws.com/1375304393091.jpg',
        variant: { name: 'r512x400', size: '512x400' } } ]

我想根据 nums(string) 键对数组进行排序。我想要对数组进行排序的方式非常简单:让相同的数字彼此相邻,即

    [ { nums: 'http://s3.amazonaws.com/1375304393109.png',
        variant: { name: 'original' } },
      { nums: 'http://s3.amazonaws.com/1375304393109.png',
        variant: { name: 'r256x200', size: '256x200' } },
      { nums: 'http://s3.amazonaws.com/2315456487896.jpg',
        variant: { name: 'original' } },
      { nums: 'http://s3.amazonaws.com/2315456487896.jpg',
        variant: { name: 'r512x400', size: '512x400' } },
      { nums: 'http://s3.amazonaws.com/1375304393091.jpg',
        variant: { name: 'r256x200', size: '256x200' } },
      { nums: 'http://s3.amazonaws.com/1375304393091.jpg',
        variant: { name: 'r512x400', size: '512x400' } } ]

不必按任何顺序排列,只要相同的数字组合即可。最快的方法是什么?

很抱歉造成混乱。我想这是原始问题的稍微复杂的版本。谁有好主意?

【问题讨论】:

  • 您是否阅读过 Stack Overflow 页面右栏中的“相关”链接?我怀疑其中一个会有所帮助。
  • .sort(function(a,b){return a.nums-b.nums});

标签: javascript arrays sorting element javascript-objects


【解决方案1】:

比较数字:

array.sort(function(a,b) { return a.nums - b.nums })

用于比较字符串(您的情况):

 array.sort(function(a,b) { return a.nums.localeCompare(b.nums) })

【讨论】:

  • 很高兴您进行了编辑。
  • 用于排序的函数必须返回一个数字,如果返回一个为负值,则a在b之前。如果 a 在 a 之前为正 b,如果它为 0,则只要涉及该函数或顺序,它们就相等
  • 这对字符串有什么作用呢?感谢您的回复!
  • @jensiepoo 之所以有效,是因为 javascript 会自动转换;你也可以使用 parseInt(string) 来确保
  • 问题已更新。我尝试了描述的方式,但似乎不起作用...感谢您的输入!
【解决方案2】:

需要将对象数组映射成字符串数组,并且需要对字符串进行排序:

array.map(function(o) {return o.nums;}).sort()

这是与您提供的示例输出最接近的结果:

["1375304393091", "1375304393091", "1375304393109", "1375304393109", "2315456487896", "2315456487896"]

【讨论】:

  • 对属性值进行排序,而不是对对象进行排序。 (OP似乎已经编辑了问题)
猜你喜欢
  • 1970-01-01
  • 2021-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-23
  • 2015-01-24
  • 1970-01-01
相关资源
最近更新 更多