You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何按指定键(favourite)对对象数组排序:将含favourite:true的对象置于数组首位

How to sort an array of fruit objects to prioritize 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 (a and b) in the array.
  • When we return -1, it tells sort() to place a before b—perfect for pushing favourites to the front.
  • Returning 1 does the opposite, putting b ahead of a.
  • Returning 0 keeps 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 09:22:27