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
382 views
in Technique[技术] by (71.8m points)

javascript - js secondary sort by different column depending on id of equal column

I have a fruit picking site. There are five staff, one does an AM shift and one does a PM shift.

At the end of the month to see who is the best worker they want to sort by who has the most (items in a day).

The secondary sort they want to use is if there is a tie then they want to compare who picked more fruit on the days where they worked together.

To handle this in the array there is a sd-??? item for every different staff member they worked with, sd-??? is worked out by appending the ids of the two staff together so when sd-111222 April and Bruno did the same day. Who ever picks more for the day also gets a 1 incremented to this field sd-111222.

This is the code I have so far see fiddle.

<script>
    var workers = [
        {"id":"111","name":"April", "most":"7","sd-111222":"1","sd-111333":"2","sd-111444":"2","sd-111555":"2"},
        {"id":"222","name":"Bruno", "most":"7","sd-111222":"2","sd-222333":"1","sd-222444":"2","sd-222555":"2"},
        {"id":"333","name":"Carlos","most":"6","sd-111333":"1","sd-222333":"2","sd-333444":"2","sd-333555":"1"},
        {"id":"444","name":"Dwayne","most":"5","sd-111444":"1","sd-222444":"1","sd-333444":"1","sd-444555":"2"},
        {"id":"555","name":"Ed",    "most":"5","sd-111555":"1","sd-222555":"1","sd-333555":"2","sd-444555":"1"}
    ];

        workers.sort(function(a,b) {
            return a.most == b.most ? b.id - a.id : b.most - a.most;

        });
    console.log(workers);
</script>

Which sorts by most then id.

What I want is something like the below logic for the secondary sort but I can't work out how to apply it.

if most is equal

get id of two equal staff

then look for sd-??? containing these two ids

and sort which is greater.

So in my example the order should be

222 (equal most as 111 but higher sd-111222)

111

333

444 (equal most as 555 but higher sd-444555)

555

How can I apply this in js?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Guess this'll do the job

return (a.most == b.most)
    ? (b["sd-" + a.id + b.id] - a["sd-" + a.id + b.id])
    : (b.most - a.most);

UPDATED FIDDLE


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

...