2

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)
    );
  });
4
  • 2
    You forget to declare the data Commented Dec 8, 2021 at 3:41
  • Updated question @AlanYu Commented Dec 8, 2021 at 4:08
  • stackoverflow.com/questions/40085998/… Commented Dec 8, 2021 at 4:38
  • What is the expected output? Commented Dec 8, 2021 at 4:49

1 Answer 1

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

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

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.