0

Suppose we have an array like

var a = [
    { name: 'Tom', surname: 'TestAsIvanov' },
    { name: 'Kate', surname: 'Ivanova' },
    { name: 'John', surname: 'Alivanov' },
    { name: 'Ivan', surname: 'Ivanov' }
]

I need to sort this array by surname field based on a provided string, e.g.:

  1. for 'iva' the pattern array should be sorted as follows
var newA = [
    { name: 'Ivan', surname: 'Ivanov' },
    { name: 'Kate', surname: 'Ivanova' },
    { name: 'John', surname: 'Alivanov' },
    { name: 'Tom', surname: 'TestAsIvanov' },
]
  1. for 'a' the pattern array should be sorted as follows
var newA = [
    { name: 'John', surname: 'Alivanov' },
    { name: 'Ivan', surname: 'Ivanov' },
    { name: 'Kate', surname: 'Ivanova' },
    { name: 'Tom', surname: 'TestAsIvanov' },
]

So arrays should be ordered by string pattern provided. How is it possible to implement this?

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
stryker
  • 149
  • 1
  • 16
  • newA.sort(function(a, b) { if (a.surname < b.surname) return -1; if (a.surname> b.surname) return 1; return 0; }); – murli2308 Oct 20 '15 at 10:57
  • @murli2308 what part of *I need to sort this array by surname field based on a provided string* you didn't understand? OP wants some kind of a filter, not only a simple alphabetical sort. – DontVoteMeDown Oct 20 '15 at 12:06
  • @DontVoteMeDown It will work directly I don't think it will require filter. I added a fiddle. http://jsfiddle.net/murli2308/mn1f4c89/ – murli2308 Oct 20 '15 at 13:07

1 Answers1

1

I've made a simple sort script for that. I don't know if it is the best way because I had to use two sort() methods, one to sort alphabetically(taken from here) and another to simulate a LIKE 'string%'(comparing to SQL) to get your condition:

var queryString = "iva";

a = a.sort(function(a, b) {
    var s1 = a.surname.toUpperCase().indexOf(queryString.toUpperCase());
    var s2 = b.surname.toUpperCase().indexOf(queryString.toUpperCase());

    return (s1 > -1 && s1 > s2);
});

Fiddle with full code

At least it worked with both examples you provided, but I'm not sure if it is all you need.

Community
  • 1
  • 1
DontVoteMeDown
  • 21,122
  • 10
  • 69
  • 105