I have a very unique situation and i am trying to sort this complex data structure in javascript.
let data = [
{
"failureNo": 1,
"rec": { "uniqId": "l-7fa-48eda0bb762f", "rotorId": "1.24.39" },
"exceptionId": 0
},
{
"failureNo": 2,
"rec": { "uniqId": "l-1577edb762f", "rotorId": "1.20.32" },
"exceptionId": 1
},
{
"failureNo": 2,
"rec": { "uniqId": "l-85fa-48eda0bb762f", "rotorId": "1.24.39" },
"exceptionId": 1
},
{
"failureNo": 3,
"rec": { "uniqId": "l-48eda0bb762f", "rotorId": "1.24.39" },
"exceptionId": 2
},
]
Here is my input above. User does some interaction in the UI and i get the below variable from that interaction. so checkedValues
variable tells me that user has selected 2 entries using checkbox. 2 entries because the collection object below has value associated to it. for e.g for key 1 it has value as new Set([ "_com.smp.1905546540", "_com.smp.3345454545" ])
,
key 2 has value as new Set([ "_com.smp.33343rf453" ])
3rd checkbox is not selected and that value is {}
in below data.
let checkedValues = new Map([
[
1,
new Set([ "_com.smp.1905546540", "_com.smp.3345454545" ])
],
[
2,
new Set([ "_com.smp.33343rf453" ])
],
[
0,
{}
],
])
So when checkbox with key 1 and 2 are selected, it is mapped to exceptionId
in the data
variable. This selection of 1 and 2 means we want the objects with exceptionId
1 and 2 to be sorted and shown first and then the rest.
So my final output should be as follows
let result = [
{
"failureNo": 2,
"rec": { "uniqId": "l-1577edb762f", "rotorId": "1.20.32" },
"exceptionId": 1
},
{
"failureNo": 2,
"rec": { "uniqId": "l-85fa-48eda0bb762f", "rotorId": "1.24.39" },
"exceptionId": 1
},
{
"failureNo": 3,
"rec": { "uniqId": "l-48eda0bb762f", "rotorId": "1.24.39" },
"exceptionId": 2
},
{
"failureNo": 1,
"rec": { "uniqId": "l-7fa-48eda0bb762f", "rotorId": "1.24.39" },
"exceptionId": 0
}
]
In order to achieve this sorting, i created a function as follows
export const sortData = (data, checkedValues) => {
const dataCopy = [...data];
return dataCopy.sort((a, b) => {
const aValues = checkedValues.get(a?.exceptionId);
const bValues = checkedValues.get(b?.exceptionId);
const aChecked = aValues ? aValues.has(a?.value) : false;
const bChecked = bValues ? bValues.has(b?.value) : false;
if (aChecked && !bChecked) return -1;
if (!aChecked && bChecked) return 1;
return a.failureNo - b.failureNo;
});
};
There is no runtime error on this function but the problem is that it doesnot sort data
at all. it just displays the data
as output as it is without sorting anything. Can someone please let me know where i am going wrong.