Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
232 views
in Technique[技术] by (71.8m points)

JavaScript: Sort array based on a permutation order?

I have a list of N elements with an array of three colors like this:

[
  { id: 1, colors: ['Red', 'Blue', 'White'] },
  { id: 2, colors: ['Red', 'Blue', 'Blue'] },
  { id: 3, colors: ['Red', 'Red', 'White'] },
  { id: 4, colors: ['Red', 'Red', 'Red'] }
]

And I would like to sort them based on this priority order, for example:

[Red,Red,Red]
[Red,Red,X]
[Red,X,Red]
[Red,X,X]
[X,Red,Red]
[X,Red,X]
[X,X,Red]

Where the 'X' indicates any other color that is not the one I indicate, in this example is 'Red'.

So an expected output, for this example would be:

[
  { id: 1, colors: ['Red', 'Red', 'Red'] },
  { id: 2, colors: ['Red', 'Red', 'White'] },
  { id: 3, colors: ['Red', 'Blue', 'White'] },
  { id: 4, colors: ['Red', 'Blue', 'Blue'] }
]

Any idea on how to approach this?

I tried finding the duplicates and sorting the parent array based on the colors, but I need to take into consideration the priority order.

elements.sort((a, b) => {
  const colorDupsA = findDuplicates(a.colors);
  const colorDupsB = findDuplicates(b.colors);
  return colorDupsB.length - colorDupsA.length;
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In the sort method, Calculate the value for each object based on permutation order and compare values.

const data = [
  { colors: ["Blue", "Blue", "Red"] },
  { colors: ["Blue", "Red", "White"] },
  { colors: ["Blue", "Blue", "White"] },
  { colors: ["Red", "Blue", "White"] },
  { colors: ["Red", "Blue", "Blue"] },
  { colors: ["Red", "Red", "White"] },
  { colors: ["Red", "Red", "Red"] },
];

const getValue = (obj) =>
  obj.colors.reduce((acc, cur) => +(cur === "Red") + acc * 10, 0);
  
data.sort((a, b) => getValue(b) - getValue(a));

console.log(data);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...