DEV Community

Indrakant Mishra
Indrakant Mishra

Posted on

Sort an array by boolean value

Hello guys, i hope you are doing really well and trying to solve bigger problems. But sometimes we get really difficult problem to solve in some interviews which can take our valuable chance đŸ˜Ĩ. Here we will be going through a problem to sort an array by boolean value without using any method and without creating and new array in O(n) time complexity.

This problem was appeared in Amazon interview and i think this will be much useful for you. So let's start 😎 -

Let's assume we have an unsorted array like this -

const response = [
{
id: 1,
name: 'Phone',
isChecked: false
},
{
id: 2,
name: 'Laptop',
isChecked: true
},
{
id: 3,
name: 'Desktop',
isChecked: false
},
{
id: 4,
name: 'Watch',
isChecked: true
}
];

and we need to place all checked items first and unchecked items at last. Below is the code for this.

let lastElementUnchecked;
for (let i = 0; i < response.length; i++) {
    if (response[i].isChecked && lastElementUnchecked !== undefined) {
        let current = response[i];
        response[i] = response[lastElementUnchecked];
        response[lastElementUnchecked] = current;
        i = lastElementUnchecked;
        lastElementUnchecked = undefined;
    } else {
        if (!response[i].isChecked && lastElementUnchecked === undefined) {
            lastElementUnchecked = i;
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

This is very simple example to understand but while interviews it can be tough to reach over.

I hope you like this, thank you for reading 😊

Top comments (1)

Collapse
 
frankwisniewski profile image
Frank Wisniewski • Edited

swap vars:

   [ response[i], response[lastElementUnchecked] ] = 
   [ response[lastElementUnchecked], response[i] ];
Enter fullscreen mode Exit fullscreen mode