-1

I have Array of object data which i want to sort objects of the Array by the specific key that is favourite. In the Array of fruits. it has some object of the fruits. I just want to sort according to the favourite key. if the key favourite:true inside object then this object will go to the top and if favourite:true is found in the more than one object,then always set top of first object which found the favourite:true key.

Input data:

[
  {
    id: 1,
    title: 'Banana',

  },
  {
    id: 2,
    title: 'Mango',
    favourite:true
  },
{
  id:3,
  title: 'Apple',
},
]

expected Output data:

[
{
    id: 2,
    title: 'Mango',
    favourite:true
  },
  {
    id: 1,
    title: 'Banana',

  },
  
{
  id:3,
  title: 'Apple',
}
]
vjtechno
  • 452
  • 1
  • 6
  • 16

3 Answers3

1

What you could do, is instanciate a new array, based on the given input values:

const favouritesFirst = [
  // Find all the favourite items & add them to the start
  ...input.filter(item => item.favourite),
  // Append all other "non favourite" items
  ...input.filter(item => !item.favourite),
]
JAM
  • 6,045
  • 1
  • 32
  • 48
1

You can use filter function to find out favourite fruits.

var arr = [
  {
    id: 1,
    title: 'Banana',

  },
  {
    id: 2,
    title: 'Mango',
    favourite:true
  },
    {
      id:3,
      title: 'Apple',
    },{
    id: 4,
    title: 'Orange',
    favourite:true
  }
];


// Filter  favourite fruits
var favoriteFruits = arr.filter(obj => obj.favourite == true);

// Filter non favourite fruits

var otherFruits = arr.filter(obj => obj.favourite !== true);

// Find sorted fruits

var sortedArr = favoriteFruits.concat(otherFruits);

Use concat functioon to join favourite and non favourite arrays. Favourite fruits will always stays at the top.

prathameshk73
  • 1,048
  • 1
  • 5
  • 16
-1
fruits.sort((a, b) => {
    if(a.favourite && !b.favourite) return 1;
    else if (!a.favourite && b.favourite) return -1;
    else return 0;
});
barbarbar338
  • 616
  • 5
  • 15
  • 1
    While this piece of code may provide a solution to the question, it's better to add context as to why/how it works. This can help future users learn and eventually apply that knowledge to their own code. You are also likely to have positive feedback/upvotes from users, when the code is explained. – Amit Verma Feb 27 '21 at 13:20