0

在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"}
    ...
]  

你会怎么做?

4

2 回答 2

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);
于 2013-04-14T18:19:16.413 回答
0

您可以按属性的升序长度对数组进行排序propName

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

Array.sort函数说明。

于 2013-04-14T18:16:40.037 回答