Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linting error: Move this array "sort" operation to a separate statement

Tags:

angular

lint

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;
    });
like image 301
Vivek Avatar asked Oct 02 '18 10:10

Vivek


2 Answers

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;
});
like image 167
Mike Kovetsky Avatar answered Nov 11 '22 05:11

Mike Kovetsky


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;
        });
like image 1
Bryan Lee Avatar answered Nov 11 '22 05:11

Bryan Lee