Created
January 30, 2017 15:52
-
-
Save danielmeneses/c059beae5586a326dc73bea4a541ed10 to your computer and use it in GitHub Desktop.
Sort Objects by field - 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
// My own implementation of merge sort (by object field) | |
var a = [ | |
{name: "Mr. Burns", age: 145}, | |
{name: "Moe", age: 37}, | |
{name: "Apu", age: 39}, | |
{name: "Carl", age: 34}, | |
{name: "Homer Simpson", age: 38}, | |
{name: "Marge Simpson", age: 36}, | |
{name: "Lisa Simpson", age: 12}, | |
{name: "Bart Simpson", age: 34}, | |
{name: "Maggie Simpson", age: 2}, | |
{name: "Krusty", age: 35} | |
]; | |
function mergeSort(input, field){ | |
var splitted = []; | |
for(var i = 0; i < input.length; i++){ | |
splitted.push([input[i]]); | |
} | |
var merged = (function merge(arr){ | |
var tempResult = []; | |
for( var i = 0; i < arr.length; i+=2 ){ | |
var left = 0, | |
right = 0, | |
result = [], | |
current = i, | |
next = i+1; | |
// for odd arrays, if doesn't has next then it's odd therefore need to push the current array | |
if( !arr[next] ){ | |
tempResult.push(arr[current]); | |
} | |
else{ | |
while( left < arr[current].length || right < arr[next].length ){ | |
// case there's only one element remaining (odd number of elements) | |
if( (left === arr[current].length | |
&& right < arr[next].length) ){ | |
result.push(arr[next][right]); | |
right++; | |
continue; | |
} | |
else if( left < arr[current].length | |
&& right === arr[next].length ){ | |
result.push(arr[current][left]); | |
left++; | |
continue; | |
} | |
var val1 = arr[current][left][field]; | |
var val2 = arr[next][right][field]; | |
if( val1 < val2 ){ | |
result.push(arr[current][left]); | |
left++; | |
} | |
else{ | |
result.push(arr[next][right]); | |
right++; | |
} | |
} | |
tempResult.push(result); | |
} | |
} | |
if( tempResult.length > 1 ) return merge(tempResult); | |
else return tempResult; | |
}(splitted)); | |
return merged[0]; | |
} | |
// start timer | |
console.time('mergeSort'); | |
// sort by age | |
var sortedArray = mergeSort(a, 'age'); // can be sorted by 'name' or other field existing in the obj | |
console.timeEnd('mergeSort'); | |
console.log(sortedArray); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment