Skip to content

Instantly share code, notes, and snippets.

@MAKIO135
Last active June 14, 2018 14:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MAKIO135/45677d38f69f695a414cd5aa0188fc0d to your computer and use it in GitHub Desktop.
Save MAKIO135/45677d38f69f695a414cd5aa0188fc0d to your computer and use it in GitHub Desktop.
sortArrayByKey.js
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