0

Here's an example of the array that I want to sort looks like.

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

I want to sort the array based on the nums(string) key. The way I want to sort the array is very simple: let the same numbers group next to each other, i.e.

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

It doesn't have to be in any order, as long as same numbers group up. What is the fastest way of doing this?

Sorry about the confusion. I guess this is slightly more complicated version of the original question. Anyone has good ideas?

jensiepoo
  • 571
  • 3
  • 9
  • 26

2 Answers2

0

for comparing numbers:

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

for comparing strings (your case):

 array.sort(function(a,b) { return a.nums.localeCompare(b.nums) })
phiresky
  • 406
  • 4
  • 15
0

You need to map the array of objects into an array of strings, and you need to sort the strings:

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

That's the closest you can get to the sample output you provided:

["1375304393091", "1375304393091", "1375304393109", "1375304393109", "2315456487896", "2315456487896"]
Ray Waldin
  • 3,217
  • 1
  • 16
  • 14