如何按属性值长度对对象数组排序

howto sort an array with objects by property value length?

本文关键字:对象 数组排序 何按 属性      更新时间:2023-09-26

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

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

我想创建一个函数,这样我就可以按属性值的长度排序数组,例如对象的属性"word"。

像这样:

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

你会怎么做?

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);

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

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

参见Array.sort功能说明