JavaScript或jQuery可以在多个条件上对JSON数组进行排序吗?

我有一个自动完成列表的潜在结果的
JSON数组.

该列表定义为:

var fundList = [ //there's lots more than this
    { "name": "Pension Managed Fund 1" },
    { "name": "Managed Property Fund 2" },
    { "name": "Retirement Managed Fund 3" },
    { "name": "Retirement Managed Fund 4" }
]

我需要按字母顺序对列表进行排序,但它也必须按输入到文本框中的值的相关性排序(触发自动完成)

例如,如果用户在文本框中键入“Managed”,则上面的列表将按如下方式排序:

Managed Property Fund 2

Pension Managed Fund 1

Retirement Managed Fund 3

Retirement Managed Fund 4

如果他们输入“退休”,列表将被排序:

Retirement Managed Fund 3

Retirement Managed Fund 4

Managed Property Fund 2

Pension Managed Fund 1

如果输入“基金”,则订单将是正常的字母顺序:

Managed Property Fund 2

Pension Managed Fund 1

Retirement Managed Fund 3

Retirement Managed Fund 4

JavaScript或jQuery中是否有任何内置功能可以执行此操作?

最佳答案 javascript有一个数组排序方法,可以将函数作为参数,这将允许您定义您希望事物排序的方式

例如

var fundList = [ //there's lots more than this
    { "name": "Pension Managed Fund 1" },
    { "name": "Managed Property Fund 2" },
    { "name": "Retirement Managed Fund 3" },
    { "name": "Retirement Managed Fund 4" }
]

funcList.sort(function(a, b){
 if (a == b)
 {
   return 0;
 }

 if (SOME CRITERIA TO SORT a AT A LOWER INDEX THEN b)
 {
   return -1;
 }

 if (SOME CRITERIA TO SORT b AT A LOWER INDEX THEN a)
 {
    return 1;
 }
});
点赞