Skip to content

Instantly share code, notes, and snippets.

@wmucheru
Created October 26, 2022 12:25
Show Gist options
  • Save wmucheru/7b7d94a3da95c4e4f1fd1f4812db58f2 to your computer and use it in GitHub Desktop.
Save wmucheru/7b7d94a3da95c4e4f1fd1f4812db58f2 to your computer and use it in GitHub Desktop.
Sort objects in array using boolean and string fields
const sortItems = () => {
const items = [
{
id: 1,
name: "Onion",
checked: true,
},
{
id: 2,
name: "Paper",
checked: true,
},
{
id: 3,
name: "Egg",
checked: false,
},
{
id: 4,
name: "Snake",
checked: true,
},
{
id: 5,
name: "Car",
checked: false,
},
{
id: 6,
name: "Apple",
checked: true,
},
{
id: 7,
name: "Pear",
// checked: true,
},
{
id: 8,
name: "Dog",
checked: true,
},
];
// Update `checked` for items without status
items.map((item) => {
item.checked = item.checked || false;
});
// Sort by name (ascending)
items.sort((a, b) => a.name.localeCompare(b.name));
// Sort by checked status (true first)
items.sort((a, b) => b.checked - a.checked);
return items;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment