Could you please help to fix linting error with below javascript function.
Error: Move this array "sort" operation to a separate statement.
item.EmployeeDetails = item.EmployeeDetails
.sort((a: IEmployeeDetails, b: IEmployeeDetails) => {
if (a.employeeType < b.employeeType) {
return 1;
}
if (a.employeeType > b.employeeType) {
return -1;
}
return 0;
});
sort() mutates the array. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype#Mutator_methods
So, try to omit the assignment operator:
item.EmployeeDetails.sort((a: IEmployeeDetails, b: IEmployeeDetails) => {
if (a.employeeType < b.employeeType) {
return 1;
}
if (a.employeeType > b.employeeType) {
return -1;
}
return 0;
});
In order to resolve this, you have to copy the original array before sorting. This is because sorting mutates the original array. You can read more about this linting error here: https://rules.sonarsource.com/typescript/RSPEC-4043
const sortedEmployeeDetails = [...item.EmployeeDetails]
.sort((a: IEmployeeDetails, b: IEmployeeDetails) => {
if (a.employeeType < b.employeeType) {
return 1;
}
if (a.employeeType > b.employeeType) {
return -1;
}
return 0;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With