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

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

No responses yet

Write a response