I need to write a function that sorts this array based on dialog_node key and previous_sibling keys. The previous_sibling of the next object matches the dialog_node value of the previous object in the array.
export function orderDialogNodes(nodes) {
// Create a mapping of dialog_node to its corresponding index in the array
const nodeIndexMap = {};
nodes.forEach((node, index) => {
nodeIndexMap[node.dialog_node] = index;
});
// Sort the array based on the previous_sibling property
nodes.sort((a, b) => {
const indexA = nodeIndexMap[a.previous_sibling];
const indexB = nodeIndexMap[b.previous_sibling];
return indexA - indexB;
});
return nodes;
}
const inputArray = [
{
type: "folder",
name: "Item 2",
dialog_node: "node_2_1702794723026",
previous_sibling: "node_9_1702956631016",
},
{
type: "folder",
name: "Item 3",
dialog_node: "node_3_1702794877277",
previous_sibling: "node_2_1702794723026",
},
{
type: "folder",
name: "Item 1",
dialog_node: "node_9_1702956631016",
previous_sibling: "node_7_1702794902054",
},
];
const orderedArray = orderDialogNodes(inputArray);
console.log(orderedArray);
2
Answers
This might work
Keeping your original code as much the same as possible, this should do what you’re looking for.
To explain it a little, when sorting, you want to return which direction you want the object to move. 1/-1 shift is left or right, and 0 keeps the order the same. Taking the difference of the indices is not going to produce the desired sorting effect.
The
!indexA
is added in there because you don’t have anode_7_...
in your sample data array.