iBlehhz
iBlehhz

Reputation: 586

Sort array of object based on another string array

I have 2 arrays

a = [
     { label:"Price", value:10 }, 
     { label:"Active", value:false },
     { label:"Category", value:"food" },
     { label:"Remarks", value:"none" }
    ];

b = ["Active","Category","Price"];

How do I sort a according to the order of b? Can I use ramda?

Something succinct like the following would be ideal

R.sortBy(R.pipe(R.prop('label'), R.indexOf(R.__, a)))(b);

Similar to this issue, except I don't have index, so I cannot use indexOf method.
Sort an array of objects based on another array of ids

Appreciate your help!

Upvotes: 0

Views: 601

Answers (1)

Rocky Sims
Rocky Sims

Reputation: 3598

There might be a more succinct option but here is how I'd do it.

const list = [
  {label:"Price", value:10},
  {label:"Active", value:false},
  {label:"Category", value:"food"},
  {label:"Remarks", value:"none"}
];
const labels = ["Active","Category","Price"];

const sorted = list.sort((a, b) => {
  const aIndex = labels.indexOf(a.label);
  const bIndex = labels.indexOf(b.label);
  return aIndex - bIndex;
});

console.log(sorted);

Upvotes: 3

Related Questions