Skip to content

Instantly share code, notes, and snippets.

@IOIO72
Created May 9, 2019 12:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save IOIO72/373dcb163ad7b2d61dad547260a0b412 to your computer and use it in GitHub Desktop.
Save IOIO72/373dcb163ad7b2d61dad547260a0b412 to your computer and use it in GitHub Desktop.
Sort items by two digit outlines
const faq = [
{
outline: "3.2",
question: "Hello John?",
answer: "Yes!"
},
{
outline: "1.1",
question: "Hello Julia?",
answer: "Hi!"
}
];
// Sort and group FAQ data
faq.getSortKey = outline => {
const leadingZero = numStr => `${numStr.length < 2 ? '0' : ''}${numStr}`;
const numbers = outline.split('.');
let ret = '';
for (let i = 0; i < numbers.length; i++) {
ret = `${ret}${leadingZero(numbers[i])}`;
}
return ret;
};
faq.sortedOutlines = faq.sort((itemA, itemB) => {
const firstOne = faq.getSortKey(itemA.outline);
const sortedPair = [firstOne, faq.getSortKey(itemB.outline)].sort();
return firstOne === sortedPair[0] ? -1 : 1;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment