This is the array what I am getting
[
{ id: 1, name: 'hello world', reference_id: null },
{ id: 2, name: 'hello world', reference_id: null },
{ id: 3, name: 'hello world', reference_id: 1 },
{ id: 4, name: 'hello world', reference_id: null },
{ id: 5, name: 'hello world', reference_id: 1 },
{ id: 6, name: 'hello world', reference_id: 2 },
]
I need to reorder this array into something similar to this.
[
{ id: 1, name: 'hello world', reference_id: null },
{ id: 3, name: 'hello world', reference_id: 1 },
{ id: 5, name: 'hello world', reference_id: 1 },
{ id: 2, name: 'hello world', reference_id: null },
{ id: 6, name: 'hello world', reference_id: 2 },
{ id: 4, name: 'hello world', reference_id: null },
]
This is the code which I tried
const parentIndex = skus?.findIndex(item => item.id === item.reference_id);
console.log(parentIndex)
if (parentIndex !== -1) {
const parentId = skus[parentIndex].id;
const parentItem = skus.splice(parentIndex, 1)[0];
const referencedItem = skus.find(item => item.id === parentId);
if (referencedItem) {
const referencedIndex = skus.indexOf(referencedItem);
skus.splice(referencedIndex + 1, 0, parentItem);
} else {
skus.push(parentItem);
}
}
When I run this code I am getting some weird unexpected results and most of the time it’s not running after the first line.
Can someone help me to resolve this issue I am struggling to find a solution.
3
Answers
A
.map()
can help to define a sorting criterion that can be applied and then lateron removed again (by a second.map()
call):OK, as requested in the comments. Here a solution in one go (just one
.sort()
call):The second version can deal with any kid of numeric id (up to "9999").
It looks like what you are after is that elements with a
reference_id
to immediately follow the element with thatid
.If that is the case then you are actually looking for a preorder traversal of the data as a tree (see: tree traversal). The following works for any level of nesting.
If however you are just looking for a primary sorting by
id
with elements that share areference_id
grouped together then you can first group-byreference_id
then sort by theid
of the first element of each group before flattening the grouped array. Here performing an initial sort byid
on a copy of theinput
array.You can do so by a custom
sort()
function: