首页 > 解决方案 > JSX:按字母顺序对对象进行排序

问题描述

我有两个看起来像这样的函数:

  const compare = (direction: string) => {
    const alphabetize = (a, b) => {
      if (direction === "alpha") {
        if (a.name < b.name) {
          return -1;
        }
        if (a.name > b.name) {
          return 1;
        }
      } else if (direction === "reverseAlpha") {
        if (a.name > b.name) {
          return -1;
        }
        if (a.name < b.name) {
          return 1;
        }
      }
      return 0;
    };
  };

  const sortAlphabetically = () => {
    setState(state => ({
      ...state,
      items: items.sort(compare("alpha"))
    }));
  };

我需要能够以compare某种方式将字符串传递给函数,告诉它以哪种方式对字母进行排序(按字母顺序,或按字母顺序倒序)。

但是这个方法不起作用,因为alphabetize从来没有这样调用过。我错过了什么?

谢谢!

标签: javascriptreactjstypescriptsorting

解决方案


[编辑] 您必须在 compare 函数中调用 alphabetize,如下所示:

const compare = () => {
  const alphabetize = () => {
   ...stuff
  }
alphabetize()
}

附带说明: JS 带有排序和反向功能:

  var sortAlphabets = (text, direction) =>
    direction === "reverseAlpha"
      ? text
          .split("")
          .sort()
          .reverse("")
          .join("")
      : text
          .split("")
          .sort()
          .join("");

推荐阅读