如何按指定键(favourite)对对象数组排序:将含favourite:true的对象置于数组首位
favourite: true items at the top Hey there, let's sort that fruit array exactly how you need it. The goal is to push all items with favourite: true to the top, while keeping their original order (so the first favourite item in your input stays first at the top), and leave the rest of the fruits in their original sequence too.
Here's a straightforward solution using JavaScript's sort() method—this works because the callback lets us define custom priority rules:
// Your input array const fruits = [ { id: 1, title: 'Banana' }, { id: 2, title: 'Mango', favourite: true }, { id: 3, title: 'Apple' } ]; // Sort with custom priority logic const sortedFruits = fruits.sort((a, b) => { // If a is a favourite and b isn't, move a up if (a.favourite && !b.favourite) return -1; // If b is a favourite and a isn't, move b up if (!a.favourite && b.favourite) return 1; // For all other cases, keep original relative order return 0; }); console.log(sortedFruits);
What this does:
- The
sort()function compares pairs of items (aandb) in the array. - When we return
-1, it tellssort()to placeabeforeb—perfect for pushing favourites to the front. - Returning
1does the opposite, puttingbahead ofa. - Returning
0keeps the items in their original relative position, so your first favourite stays first, and non-favourite fruits don't get jumbled up.
Running this code will give you exactly the output you want:
[ { id: 2, title: 'Mango', favourite:true }, { id: 1, title: 'Banana' }, { id:3, title: 'Apple' } ]
Quick tweak for edge cases:
If some fruits might have favourite: false (instead of just missing the key), you can make the check a bit more explicit with Boolean() to handle both scenarios cleanly:
const sortedFruits = fruits.sort((a, b) => { const aIsFave = Boolean(a.favourite); const bIsFave = Boolean(b.favourite); if (aIsFave && !bIsFave) return -1; if (!aIsFave && bIsFave) return 1; return 0; });
This way, even if an item has favourite: false, it'll be treated the same as items without the key—no unexpected behavior.
内容的提问来源于stack exchange,提问作者vjtechno

