Home > Blockchain >  How to use the filter method in javascript?
How to use the filter method in javascript?

Time:05-30

I am using filter method to get a selected item from an option list. But it gives me the following error:

Array.prototype.filter() expects a value to be returned at the end of arrow function.eslintarray-callback-return

My function is the following:

const getSelectValue = () => {
        const selectedList = get(state, `${name}`, []);
        if (isEmpty(selectedList) || isEmpty(options)) {
            return [];
        }
        const selectedSet = new Set(selectedList);
        return options.filter(item => {
            if(item.value !=="Add type") 
                return selectedSet.has(item.value); 
        }  );
    };

Anyone who can spot the missing thing here?

CodePudding user response:

The arrow function supplied as filter callback should always return some value by this linting rule. But here...

item => {
  if(item.value !=="Add type") {
    return selectedSet.has(item.value); 
  }
);

... there are no return statements if if condition is falsy; hence the error. You can fix this in many different ways; the most straightforward one is just adding explicit return false; at the end of the function. Another approach is combining two conditions:

item => {
  return item.value !=="Add type" && selectedSet.has(item.value) 
}

CodePudding user response:

Just return a value if statement is false (after if } enclosing bracket) and error should be gone.

CodePudding user response:

you have to change like this :

const getSelectValue = () => {
        const selectedList = get(state, `${name}`, []);
        if (isEmpty(selectedList) || isEmpty(options)) {
            return [];
        }
        const selectedSet = new Set(selectedList);
        return options.filter(item => {
           
                return item.value !=="Add type" && selectedSet.has(item.value); 
        }  );
    };
  • Related