2

How to sort the array of json data having letters and digits?

JS:

function sortOn(property) {
        return function (a, b) {
            if (a[property] < b[property]) {
                return -1;
            } else if (a[property] > b[property]) {
                return 1;
            } else {
                return 0;
            }
        }
    }

  var data = [{"id":1,name:"text10"},
              {"id":4,"name":"text1"}, {"id":4,"name":"text19"},     {"id":4,"name":"text2"}, {"id":4,"name":"text20"},
               {"id":5,"name":"book"}];
data.sort(sortOn('name'));
console.log(data);// when I print the JSON getting book,text1,text10..

//But I have to want to show the json as book,text1,text2...

Any one can help me how to sort the name thing having both letters and digits

Please find the jsfiddle for reference.

Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
lakshmi
  • 43
  • 2
  • 1
    What you're looking for is a _natural_ sort algorithm, which you can find by googling – sahbeewah Nov 13 '15 at 12:36
  • 1
    Possible duplicate of [Javascript : natural sort of alphanumerical strings](http://stackoverflow.com/questions/2802341/javascript-natural-sort-of-alphanumerical-strings) – Roman Hocke Nov 13 '15 at 12:44
  • Could you send me the any sample code , so that I will apply to my code? – lakshmi Nov 13 '15 at 12:47

1 Answers1

0

Very simplistic implementation. Sort on either the number in the name and if it doesn't exist, use the full name. Could be sped up by caching the parseInt || name comparison.

var result = data.sort(function ( a, b ) {
    var first = parseInt(/\d+/g.exec(a.name), 10) || a.name,
        second = parseInt(/\d+/g.exec(b.name), 10) || b.name;
    if (first > second) return 1;
    else if (first === second) return 0;
    else return -1;
    return -1
});
Shilly
  • 8,511
  • 1
  • 18
  • 24