【问题标题】:Sort by multiple strings in Array using Javascript使用Javascript按数组中的多个字符串排序
【发布时间】:2022-01-13 02:02:38
【问题描述】:

我正在尝试按多个字符串对数组进行排序,但结果很短。这是可能的还是在下面写一些东西来实现这一点?

不起作用:

const colorArr = ["Red", "Blue", "Green"]
const colorMap = colorArr.map((a) => a);

const newArr = data.sort((a, b) => {
  return (
    (a.credits.credit.value !== colorMap) - (b.credits.credit.value !== colorMap)
  );
});

console.log("newArr========", newArr)

这可行,但条件越多,时间就越长...

const data = [
  {
    credits: {
      credit: {
        value: "Red",
      },
    },
  },
  {
    credits: {
      credit: {
        value: "Blue",
      },
    },
  },
  {
    credits: {
      credit: {
        value: "Green",
      },
    },
  },
  {
    credits: {
      credit: {
        value: "Red",
      },
    },
  },
  {
    credits: {
      credit: {
        value: "Red",
      },
    },
  },
  {
    credits: {
      credit: {
        value: "Blue",
      },
    },
  },
];


const nameActor = "Red";
const nameEp = "Blue";
const nameDirector = "Green";

  const newArr = data.sort((a, b) => {
    return (
      (a.credits.credit.value !== nameActor) - (b.credits.credit.value !== nameActor) ||
      (a.credits.credit.value !== nameEp) - (b.credits.credit.value !== nameEp) ||
      (a.credits.credit.value !== nameDirector) - (b.credits.credit.value !== nameDirector)
    );
  });

【问题讨论】:

标签: javascript arrays sorting


【解决方案1】:
const colorOrder = ['Red', 'Blue', 'Green'];

const order = data.sort(
  (a, b) =>
    colorOrder.indexOf(a.credits.credit.value) -
    colorOrder.indexOf(b.credits.credit.value)
);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-19
    • 2013-03-31
    • 1970-01-01
    • 2020-08-14
    • 2017-02-25
    • 1970-01-01
    • 1970-01-01
    • 2021-08-08
    相关资源
    最近更新 更多