0

I have used lwc data table and have set columns as below.

const columns = [
{label: 'Name', fieldName: 'Name', type: 'text', sortable: true},
{label: 'Active', fieldName: 'active', type: 'boolean', sortable: true}
];

then over a sort function I am getting the fieldName and tryoing to sort.

if(typeof fieldname === 'string'){
        data.sort((a,b) => {
            let valueA = key(a) ? key(a).toLowerCase() : '';
            let valueB = key(b) ? key(b).toLowerCase() : '';
            return reverse * ((valueA > valueB) - (valueB > valueA));
        });
    }else{
        data.sort(function(a,b){
            var a = key(a) ? key(a) : '';
            var b = key(b) ? key(b) : '';
            return reverse * ((a>b) - (b>a));
        });
    }

"if(typeof fieldname === 'string')" is always returning data type as string and not returning the Active field as boolean.

Basically I am trying to implement sort function where I am trying to sort text and checkbox values.

  • 4
    Note that js is a case-sensitive language. Thus fieldName !== fieldname – Oleh Berehovskyi Feb 17 '20 at 10:44
  • it worked like below by converting all boolean values into string: let valueA = key(a) ? key(a).toString().toLowerCase() : ''; let valueB = key(b) ? key(b).toString().toLowerCase() : ''; – Harry Feb 17 '20 at 11:15
0

The typeof operator returns the evaluated type of variable passed in (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof)

In your case, you're passing in a value of fieldName which is, in truth, string for both your columns:

const columns = [
{label: 'Name', fieldName: 'Name', type: 'text', sortable: true},
{label: 'Active', fieldName: 'active', type: 'boolean', sortable: true}
];
typeof columns[0] /// 'string'
typeof columns[1] /// 'string'

What you meant to do was check if columns[index].type equals to your expected data, e.g. like so

// it is not clear where you get fieldName from, so might as well get type there, too
if(type === 'string'){ 
        // do whatever
    }else{
       // do whatever again
    }

Further, as you noted in your comments, your sorting methods are very close and can be merged like so:

function valueConverter(val) => val ? (typeof val === 'string' ? val : val.toString()).toLowerCase() : '';

  data.sort((a,b) => {
            let valueA = valueConverter(key(a));
            let valueB = valueConverter(key(b));
            return reverse * ((valueA > valueB) - (valueB > valueA));
        });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.