如何按属性值长度对对象进行排序?

时间:2013-04-14 18:12:21

标签: javascript

在javascript中,我有以下带有对象的数组:

var defaultSanitizer = [
    {"word": "large", "replaceWith":"L"},
    {"word": "os", "replaceWith":"One Size"},  
    {"word": "xlarge", "replaceWith":"XL"},
    {"word": "o/s", "replaceWith":"One Size"},
    {"word": "medium", "replaceWith":"M"}
    ...
];

(实际上这个数组要大得多)

我想创建一个函数,这样我就可以通过属性值的长度对数组进行排序,例如:对象的属性“单词”。

这样的事情:

function sortArrByPropLengthAscending(arr, property) {

    var sortedArr = [];

    //some code

    return sortedArr;

}

如果我要运行sortArrByPropLengthAscending函数(defaultSanitizer,“word”),它应该返回一个如下所示的排序数组:

sortedArr = [        
    {"word": "os", "replaceWith":"One Size"},  
    {"word": "o/s", "replaceWith":"One Size"},
    {"word": "large", "replaceWith":"L"},
    {"word": "xlarge", "replaceWith":"XL"},        
    {"word": "medium", "replaceWith":"M"}
    ...
]  

你会怎么做?

2 个答案:

答案 0 :(得分:1)

function sortMultiDimensional(a,b)
{
    return ((a.word.length < b.word.length) ? -1 : ((a.word.length > b.word.length) ? 1 : 0));
}

var defaultSanitizer = [
    {"word": "large", "replaceWith":"L"},
    {"word": "os", "replaceWith":"One Size"},  
    {"word": "xlarge", "replaceWith":"XL"},
    {"word": "o/s", "replaceWith":"One Size"},
    {"word": "medium", "replaceWith":"M"}
];

defaultSanitizer.sort(sortMultiDimensional);
console.log(defaultSanitizer);

答案 1 :(得分:0)

您可以使用以下属性propName的升序长度对数组进行排序:

function sortArray(array, propName) {
    array.sort(function(a, b) {
        return a[propName].length - b[propName].length;
    });
}

请参阅Array.sort函数的说明。