如何根据名称对此JavaScript对象进行排序,然后按相关性排序?

时间:2011-08-23 15:17:31

标签: javascript json sorting

我之前问过以下问题:Can JavaScript or jQuery sort a JSON array on multiple criteria?

我想我可能在提出问题时犯了一个错误,因为我指定了一个JavaScript数组,而不是一个对象,而且看起来这种差异是我遇到的困难的根源。

我的页面上存在由JSON定义的以下对象,该对象用于自动完成功能:

var fundList = [
    { "name": "Pension Managed Fund 1", "id": 21, "cid": "N0", "dupId": 53 },
    { "name": "Managed Property Fund 2", "id": 407, "cid": "N0", "dupId": 58 },
    { "name": "Retirement Managed Fund 3", "id": 640, "cid": "N0", "dupId": 111 },
    { "name": "Retirement Managed Fund 4", "id": 752, "cid": "N0", "dupId": 115 }
]

我需要根据名称按字母顺序对这些项目进行排序,但它们也必须按照与输入到文本框中的值的相关性进行排序(这会触发自动完成)

例如,如果用户在文本框中键入“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

如果能够根据我指定的名称和标准对此进行排序,我需要做什么?我尝试使用上一个问题中建议的fundList.sort(new function(a, b),但是返回一个函数未定义的错误。

2 个答案:

答案 0 :(得分:0)

您应该认真阅读javascript中的how to sort arrays

这是一种方法:

var fundList = [
        { "name": "Pension Managed Fund 1", "id": 21, "cid": "N0", "dupId": 53 },
        { "name": "Managed Property Fund 2", "id": 407, "cid": "N0", "dupId": 58 },
        { "name": "Retirement Managed Fund 3", "id": 640, "cid": "N0", "dupId": 111 },
        { "name": "Retirement Managed Fund 4", "id": 752, "cid": "N0", "dupId": 115 }
    ],
    textEntered = 'Managed';

fundList.sort(function(a, b)
{
    var aStart = a.name.match(new RegExp('^'+textEntered, 'i')) || [],
        bStart = b.name.match(new RegExp('^'+textEntered, 'i')) || [];

    if ( aStart.length != bStart.length ) return bStart.length - aStart.length;

    else return a.name > b.name ? 1 : -1;
});

http://jsfiddle.net/txJVB/3/

答案 1 :(得分:0)

var fundList = [
        { "name": "Pension Managed Fund 1", "id": 21, "cid": "N0", "dupId": 53 },
        { "name": "Managed Property Fund 2", "id": 407, "cid": "N0", "dupId": 58 },
        { "name": "Retirement Managed Fund 3", "id": 640, "cid": "N0", "dupId": 111 },
        { "name": "Retirement Managed Fund 4", "id": 752, "cid": "N0", "dupId": 115 }
    ],
    textEntered = 'Managed';

fundList.sort(function(a, b)
{
    ai = a.name.indexOf(textEntered);
    bi = b.name.indexOf(textEntered);
    if(ai>=0 && bi<0) return -1;
    else if(bi>=0 && ai<0) return 1;
    else return a.name - b.name;
});