DEV Community

Indrakant Mishra
Indrakant Mishra

Posted on

1

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 😊

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay