I have a data array -
let data = ['x1', 'x2', 'x3', 'x4'];
and another 2d array that specifies the sort order of the elements within the data array -
let order =
[
['x4', 'x1'],
['x3', 'x2']
];
EDITED: Removed the conflicting rules from the order array
The 'order' array provides ordering data for only some of the elements in the data array. The order of items that are not provided in the 'order' array doesn't matter.
I am using the below logic -
console.log("Before sort:", data);
data.sort((a, b) => {
console.log("a:", a, ",", "b:", b);
for (orderRow of order) {
if (orderRow.includes(a) && orderRow.includes(b)) {
return orderRow.indexOf(a) - orderRow.indexOf(b);
}
}
return 0;
});
console.log("After sort:", data);
Below is the output -
Before sort: [ 'x1', 'x2', 'x3', 'x4' ]
a: x2 , b: x1
a: x3 , b: x2
a: x3 , b: x2
a: x3 , b: x1
a: x4 , b: x3
a: x4 , b: x2
After sort: [ 'x1', 'x3', 'x2', 'x4' ]
The logic doesnt work (x4 needs to be before x1 as mentioned in the 1st item of order array) because the x1,x4 pair is never directly compared by sort.
Looking for suggestions.
EXPECTED RESULT: [ 'x4', 'x3', 'x2', 'x1' ] ==> x4 must come before x1 [order array - item 1]
OR ["x4", "x1", "x3", "x2"] ==> satisfies all the rules from order array i,e x3 is before x2 & x4 is before x1
NOTE: The order array may have variable number of rows with variable items within each row. If conflicting sort order is specified by multiple rows, then the sort order provided by the row that at lower index applies.