Reordering JavaScript array based on boolean property

Hey everyone, I’m working on a JavaScript project and I’m stuck. I’ve got an array of objects, each with an ID and a boolean ‘last’ property. I want to sort this array so that the object with ‘last’ set to true appears at the end. Here’s what I have so far:

let items = [
  { name: 'Apple', isLast: false },
  { name: 'Banana', isLast: true },
  { name: 'Cherry', isLast: false },
  { name: 'Date', isLast: false },
  { name: 'Elderberry', isLast: false }
];

items.forEach(item => console.log(item.name));

Right now, this just logs the names in order. But I want it to print all the false ones first, then the true one last. So it should look like:

Apple
Cherry
Date
Elderberry
Banana

Any ideas on how to do this? I’ve tried a few things but can’t seem to get it right. Thanks in advance for any help!

I’ve encountered a similar situation in one of my projects. Here’s a straightforward approach that should work for you:

items.sort((a, b) => a.isLast === b.isLast ? 0 : a.isLast ? 1 : -1);
items.forEach(item => console.log(item.name));

This sorting method compares the ‘isLast’ property of two items. If both are the same (either both true or both false), it keeps their relative order. If ‘a’ is last and ‘b’ isn’t, ‘a’ moves to the end. If ‘b’ is last and ‘a’ isn’t, ‘b’ moves to the end.

This solution is efficient and doesn’t require creating a new array. It modifies the original array in-place, which can be beneficial for performance, especially with larger datasets.

Hope this helps solve your problem!

hey mate, I think i got a quick fix for ya. try this:

items.sort((a, b) => a.isLast ? 1 : -1);
items.forEach(item => console.log(item.name));

should do the trick. it’ll push the last one to the end and keep the rest in order. lemme know if it works!

I’ve dealt with similar sorting issues before. Here’s an alternative approach you might find useful:

const sortedItems = […items].sort((a, b) => Number(a.isLast) - Number(b.isLast));
sortedItems.forEach(item => console.log(item.name));

This method creates a new sorted array without modifying the original. It converts the boolean to a number (false becomes 0, true becomes 1) for comparison. This approach is clean, efficient, and maintains the original order of false items.

Remember, if you need to preserve the original array, this is a good option. If not, the in-place sorting methods suggested by others work well too. Choose based on your specific requirements.