Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

sorting - Javascript how to sort by dynamic property

I have the following array, and I want to sort it following these rules

  1. Primary true and shouldPrioritize true
  2. Primary true and shouldPrioritize false
  3. Primary false and shouldPrioritize true
  4. Primary false and shouldPrioritize false
const array = [{
  primary: true
  shouldPrioritize: false,
},
{
  primary: true
  shouldPrioritize: true,
}
{
  primary: false
  shouldPrioritize: true,
}
{
  primary: false
  shouldPrioritize: false,
}
]

What's the easiest way of using sort to match the rules? If we remove one of the items we should sort accordingly too.

question from:https://stackoverflow.com/questions/65848756/javascript-how-to-sort-by-dynamic-property

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

1 Reply

0 votes
by (71.8m points)

Just take the deltas of the booleans.

const
    array = [{ primary: true, shouldPrioritize: false }, { primary: true, shouldPrioritize: true }, { primary: false, shouldPrioritize: true }, { primary: false, shouldPrioritize: false }];
    
array.sort((a, b) => b.primary - a.primary || b.shouldPrioritize - a.shouldPrioritize);

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...