Skip to content

Instantly share code, notes, and snippets.

@wcarss
Created January 28, 2019 21:45
Show Gist options
  • Save wcarss/ac8162f7ee045be4e0c1e8a373f6c647 to your computer and use it in GitHub Desktop.
Save wcarss/ac8162f7ee045be4e0c1e8a373f6c647 to your computer and use it in GitHub Desktop.
sort an array of objects by another array's values in js
const ordering_arr = ["primary", "home", "business", "camp", "outhouse", "mars", "pluto"];
const to_sort = [
{
"address": "1",
"type": "primary"
},
{
"address": "2",
"type": "home"
},
{
"address": "2a",
"type": "home"
},
{
"address": "2b",
"type": "home"
},
{
"address": "3",
"type": "business"
},
{
"address": "3a",
"type": "business"
},
{
"address": "3b",
"type": "business"
},
{
"address": "3c",
"type": "business"
},
{
"address": "4",
"type": "camp"
},
{
"address": "4a",
"type": "camp"
},
{
"address": "4b",
"type": "camp"
},
{
"address": "4c",
"type": "camp"
},
{
"address": "4d",
"type": "camp"
},
{
"address": "5",
"type": "outhouse"
},
{
"address": "5a",
"type": "outhouse"
},
{
"address": "5b",
"type": "outhouse"
},
{
"address": "5c",
"type": "outhouse"
},
{
"address": "6",
"type": "pluto"
},
];
const sort_by_types = (contents, ordering) => {
const new_contents = [...contents],
ordering_lookup = {};
ordering.forEach((elem, index) => {
ordering_lookup[elem] = index;
});
new_contents.sort((a, b) => {
return ordering_lookup[a.type] - ordering_lookup[b.type]
});
return new_contents;
}
/**
* Shuffles array in place.
* @param {Array} a items An array containing the items.
*/
function shuffle(a) {
var j, x, i;
for (i = a.length - 1; i > 0; i--) {
j = Math.floor(Math.random() * (i + 1));
x = a[i];
a[i] = a[j];
a[j] = x;
}
return a;
}
shuffle(to_sort);
console.log(sort_by_types(to_sort, ordering_arr));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment