Say I have an order which is just an ordered list that references the array of objects with a sectionId. I'd like the items missing from the order list to be appended to the end of the sorted array. However my example below the missing items are put at the top of the list - help appreciated!
const orders = [
[
"one",
"two",
"three",
],
[
"two",
"three",
"one",
],
[
"three",
"one",
"two",
]
]
const sections = {
0: [
{
"sectionId": "a"
},
{
"sectionId": "two"
},
{
"sectionId": "z"
},
{
"sectionId": "three"
},
{
"sectionId": "one"
},
],
1: [
{
"sectionId": "a"
},
{
"sectionId": "three"
},
{
"sectionId": "one"
},
{
"sectionId": "z"
},
{
"sectionId": "two"
},
],
2: [
{
"sectionId": "z"
},
{
"sectionId": "a"
},
{
"sectionId": "two"
},
{
"sectionId": "three"
},
{
"sectionId": "one"
},
]
}
const outcomes = {
0: [
{
"sectionId": "one"
},
{
"sectionId": "two"
},
{
"sectionId": "three"
},
{
"sectionId": "a"
},
{
"sectionId": "z"
},
],
1: [
{
"sectionId": "two"
},
{
"sectionId": "three"
},
{
"sectionId": "one"
},
{
"sectionId": "a"
},
{
"sectionId": "z"
},
],
2: [
{
"sectionId": "three"
},
{
"sectionId": "one"
},
{
"sectionId": "two"
},
{
"sectionId": "z"
},
{
"sectionId": "a"
},
],
}
// function
const generateOrderedSections = (sections, order) => {
return sections.sort((a, b) => {
const aIndex = order.indexOf(a.sectionId)
const bIndex = order.indexOf(b.sectionId)
const sortOrder = aIndex > 0 && aIndex > bIndex ? 1 : -1
// console.log(aIndex, a.sectionId, bIndex, b.sectionId, sortOrder)
return sortOrder;
})
}
// test cases
orders.forEach((order, index) => {
const section = sections[index]
const test = generateOrderedSections(section, order)
const result = JSON.stringify(test)
const outcome = JSON.stringify(outcomes[index])
if (result === outcome) {
console.log(index, 'passed')
} else {
console.log('-------------')
console.log('failed')
console.log('-------------')
console.log('expected')
console.log(outcomes[index])
console.log('\nresult')
console.log(test)
}
})
'z'before'a'in thei first part?