After finding this sorting function as the best answer to my question, I tested it with example data and it worked perfectly. However, when I tried it with my actual data, it didn't work as expected and I'm not sure why.
You can view my data here: JSON
The data consists of objects like this:
"Montana": {
"superiors": [
"Massachusetts",
"Oklahoma",
"New Mexico"
],
"inferiors": [
"North Carolina"
]
}
These objects serve as guidelines for the sorting function. For instance, in this case, Montana
should be ranked higher than North Carolina
, but below Massachusetts
, Oklahoma
, and New Mexico
(note that this isn't related to geography).
Important Note:
- This is not related to the order of object keys.
While the sorting algorithm mostly works, there are instances where it doesn't work as expected. For example,
states['North Carolina'].superiors.includes('Ohio') === true
so why is 'Ohio'
listed below 'North Carolina'
?
fetch('https://api.npoint.io/7571e85ef470a2a7f189')
.then(data => data.json())
.then(states => {
function mySort(arr) {
const scores = Array(arr.length).fill(0);
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr.length; j++) {
if (i === j) continue;
const a = arr[i];
const b = arr[j];
if (states[a].inferiors.includes(b) || states[b].superiors.includes(a)) scores[j]++;
else if (states[b].inferiors.includes(a) || states[a].superiors.includes(b)) scores[i]++;
}
}
// Sort arr by scores:
return arr.map((val, i) => [scores[i], val])
.sort((a, b) => a[0] - b[0])
.map(pair => pair[1]);
}
const names = Object.keys(states);
console.log(mySort(names));
/*
// sorted output here...
*/
// states['North Carolina'].superiors.includes('Ohio') === true
// so why is 'Ohio' listed beneath 'North Carolina'?
});
If you're unable to access the original data, here is the JSON for reference:
{"Iowa":{"inferiors":[],"superiors":["Alaska","Oklahoma","California","Hawaii","New Jersey","Virginia","Florida","Washington","Minnesota","Texas","Idaho","Alabama","Ohio"]},"Ohio":... (truncated for brevity)