Last active
June 14, 2018 14:27
-
-
Save MAKIO135/45677d38f69f695a414cd5aa0188fc0d to your computer and use it in GitHub Desktop.
sortArrayByKey.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function sortArrayByKey( arr, key ){ | |
let keyPath = key.split( '.' ); | |
return arr.map( ( e, i ) => { | |
let value = e[ keyPath[ 0 ] ]; | |
for( let index = 1; index < keyPath.length; index ++ ){ | |
value = value[ keyPath[ index ] ]; | |
} | |
return { | |
index: i, | |
value: value | |
}; | |
} ) | |
.sort( ( a, b ) => +( a.value > b.value ) || +( a.value === b.value ) - 1 ) | |
.map( e => arr[ e.index ] ); | |
} | |
/* | |
// example usage: | |
console.clear(); | |
var log = console.log; | |
var array = [ 'Delta', 'alpha', 'CHARLIE', 'bravo' ].map(function(word){ | |
return { | |
letter: word, | |
values: { | |
value1: Math.round(Math.random() * 10 ), | |
value2: Math.round(Math.random() * 10 ) | |
} | |
}; | |
}); | |
log( array ); | |
log( '////////////////////////////////' ); | |
var result = sortArrayByKey( array, 'letter' ); | |
log( result ); | |
log( '////////////////////////////////' ); | |
var result = sortArrayByKey( array, 'values.value2' ); | |
log( result ); | |
log( '////////////////////////////////' ); | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment