JavaScript Interview Question: Find the number of 1s and 0s from the array

Vigo Webs
1 min readJul 26, 2023

You have been given an array of integers that consists only 1s and 0s. Your task is to find the total number 1s and 0s in the array.

Example Input:
[1, 0, 1, 0, 0, 1, 1, 0]

Expected Output:
Total 1s are 4.
Total 0s are 4.

Sounds easy, right?

But wait, there is one condition that you should not use any conditional operators like “if” or “ternary operator”. Interesting right?

The easiest way to find the solution is sum all the numbers in the array and subtract it from the array length. Since we only have 0s and 1s, the sum of the array is equal to the number of 1s and the difference from array length is equal to the number of 0s.

Sounds easy, right? lets code it now.

const findOnesAndTwos = (array) => {
const sum = array.reduce((acc, num) => acc + num, 0);
console.log(`Total 1s are: ${sum}`);
console.log(`Total 0s are: ${array.length - sum}`);
};

findOnesAndTwos([1, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0])
// Total 1s are: 7
// Total 0s are: 6

Check it out on our YouTube

--

--