1

I have a class in which their are two methods handleChange(e) and cardClick(e) and i want to sort an object array both of the functions. My code is:

handleChange(e){
arr.sort(compare);
            function compare(a, b){
                if(a.population === 'unknown')
                    return 1;
                if(b.population === 'unknown')
                    return -1;
                if(parseInt(a.population) < parseInt(b.population))
                    return 1;
                else if(parseInt(a.population) > parseInt(b.population))
                    return -1;
                else
                    return 0;
            }
}

and

cardClick(e){
arr.sort(compare);
            function compare(a, b){
                if(a.population === 'unknown')
                    return 1;
                if(b.population === 'unknown')
                    return -1;
                if(parseInt(a.population) < parseInt(b.population))
                    return 1;
                else if(parseInt(a.population) > parseInt(b.population))
                    return -1;
                else
                    return 0;
            }
}

I have to write the compare function definition in both handleChange and cardClick. Is their any way so that i don't have to write it twice, and i can use it in both functions.

1 Answer 1

1

You can define the function outside of the class and use it in both event handlers.

Example

function compare(a, b) {
  if (a.population === "unknown") return 1;
  if (b.population === "unknown") return -1;
  if (parseInt(a.population) < parseInt(b.population)) return 1;
  else if (parseInt(a.population) > parseInt(b.population)) return -1;
  else return 0;
}

class App extends React.Component {
  handleChange = e => {
    arr.sort(compare);
    // ...
  };

  cardClick = e => {
    arr.sort(compare);
    // ...
  };

  render() {
    // ...
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.