Home > front end >  Sort by multiple strings in Array using Javascript
Sort by multiple strings in Array using Javascript

Time:12-08

I am trying to sort an array by multiple strings but coming up short. Is this possible or is writing something below the only to achieve this?

Doesn't work:

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)

This works, but can get very lengthy the more conditions...

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)
    );
  });

CodePudding user response:

const colorOrder = ['Red', 'Blue', 'Green'];

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