I came across a problem: I have data coming from a database that are related to each other so that each field has two others - one referring to the previous field (in the table) and the other to the next field.
Something like this:
... demais campos
id
prev_id
next_id
I need to sort out those objects that come from the database in some way. I tried using the .sort()
method of JavaScript, but I did not get any success:
const positions = [
{ name: 'Segundo', id: 2, prev: 1, next: 3 },
{ name: 'Quarto', id: 4, prev: 3, next: 4 },
{ name: 'Primeiro', id: 1, prev: 1, next: 2 },
{ name: 'Terceiro', id: 3, prev: 2, next: 3 }
]
/**
* Deve ficar assim:
*
* { name: 'Primeiro', id: 1, prev: 1, next: 2 },
* { name: 'Segundo', id: 2, prev: 1, next: 3 },
* { name: 'Terceiro', id: 3, prev: 2, next: 3 },
* { name: 'Quarto', id: 4, prev: 3, next: 4 }
*/
const newArray = positions.sort((a, b) => {
if (a.prev === b.id) return 1
if (a.next === b.id) return -1
return 0
})
console.log(newArray)
I've put a small example above using an initial array and in a comment, the array that needs to be reached through sorting.
It's important to note that because the data comes from a database, I can not necessarily assume that the IDs will be in order.
Another example to illustrate this situation:
const positions = [
{ name: 'Quarto', id: 3, prev: 1, next: 3 },
{ name: 'Primeiro', id: 5, prev: 5, next: 7 },
{ name: 'Segundo', id: 7, prev: 5, next: 1 },
{ name: 'Terceiro', id: 1, prev: 7, next: 3 }
]
// Deve ficar:
const sorted = [
{ name: 'Primeiro', id: 5, prev: 5, next: 7 },
{ name: 'Segundo', id: 7, prev: 5, next: 1 },
{ name: 'Terceiro', id: 1, prev: 7, next: 3 },
{ name: 'Quarto', id: 3, prev: 1, next: 3 }
]
Another addendum is that if the item is first in the list, it gets its own ID in the prev
field. Something similar happens with the latter, which gets its own ID in the next
field.