Howto Sort An Array With Objects By Property Value Length?
In javascript I have the following array with objects: var defaultSanitizer = [ {'word': 'large', 'replaceWith':'L'}, {'word': 'os', 'replaceWith':'One Size'}, {'word
Solution 1:
functionsortMultiDimensional(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);
Solution 2:
You can sort the array in place by the ascending length of property propName
with:
functionsortArray(array, propName) {
array.sort(function(a, b) {
return a[propName].length - b[propName].length;
});
}
See the description of the Array.sort
function.
Post a Comment for "Howto Sort An Array With Objects By Property Value Length?"