简体   繁体   中英

sort array of objects based on string

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, eg:

  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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM