sort array of objects based on string

前端 未结 1 487
面向向阳花
面向向阳花 2021-01-28 10:01

Suppose we have an array like

var a = [
    { name: \'Tom\', surname: \'TestAsIvanov\' },
    { name: \'Kate\', surname: \'Ivanova\' },
    { name: \'John\', sur         


        
相关标签:
1条回答
  • 2021-01-28 10:28

    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.

    0 讨论(0)
提交回复
热议问题