-1

I would like to sort

array = ['3 a','4 v','2 x','1 j','2 x']

The result should be

array = ['1 j','2 x','2 x','3 a','4 v']

It should be use only number to sorting.

any ideas?

Dan
  • 35
  • 4

2 Answers2

2

Like this

var data = ['3 a','4 v','2 x','1 j','2 x'];

data.sort(function (a, b) {
  return parseInt(a) - parseInt(b);
});

console.log(data);

If data looks like this ['a 3','v 5','2 x','1 j','2 x']; you can use this approach

data.sort(function (a, b) {
  a = (a = a.match(/\d+/)) && a[0];
  b = (b = b.match(/\d+/)) && b[0];

  return a - b;
});
Oleksandr T.
  • 76,493
  • 17
  • 173
  • 144
0

If you have other formatting than "number blankspace letter" you could use this:

var data = ['3 a','4 v','2 x','1 j','2 x', '100 y'],
    regex = /[0-9]+/g

data.sort(function (a, b) {
  return (a.match(regex)[0] || 0) - (b.match(regex)[0] || 0)
});

console.log(data);

Works for "jdhsbfyus00789iutasvd iush d" also.

It takes the first number, e. g. if it was a string like this: "hfjf02 uy fdi88" it would have 2 as value.

You could modify the regex certainly if you would search for something else.

Hope it helps :)

luxas
  • 438
  • 2
  • 7