I'm trying to make a more advanced scientific calculator. I am having trouble figuring out how to do this type of calculation. I have an array of numbers and I want to check which of the given numbers are divisible by 3.
I would like both the collection of numbers divisible by 3 and the count of those numbers.
For example, on input of:
const collection = [
{ text: "0", value: 0 },
{ text: "1", value: 1 },
{ text: "2", value: 2 },
{ text: "3", value: 3 },
{ text: "4", value: 4 },
{ text: "5", value: 5 },
{ text: "6", value: 6 },
{ text: "7", value: 7 },
{ text: "8", value: 8 },
{ text: "9", value: 9 },
{ text: "10", value: 10 },
{ text: "11", value: 11 },
{ text: "12", value: 12 },
];
I would like to get output like:
"There are 5 divisible numbers by 3: 0, 3, 6, 9, 12"
How can I do that?
Use the modulo operator with for loops, denoted by %
I have an array of numbers and I want to check which of the given numbers are divisible by 3.
You have an array of objects holding a Number on the value key.
We can get the desired output by
filter() only devisible by 3filter(c => c.value % 3 === 0)map() to only get number from value keyjoin() to separate results with an commaconst collection = [{ text: "0", value: 0 }, { text: "1", value: 1 }, { text: "2", value: 2 }, { text: "3", value: 3 }, { text: "4", value: 4 }, { text: "5", value: 5 }, { text: "6", value: 6 }, { text: "7", value: 7 }, { text: "8", value: 8 }, { text: "9", value: 9 }, { text: "10", value: 10 }, { text: "11", value: 11 }, { text: "12", value: 12 }, ];
let res = collection.filter(c => c.value % 3 === 0).map(o => o.value);
console.log(`There are ${res.length} divisible numbers by 3: ${res.join(', ')}`);
There are 5 divisible numbers by 3: 0, 3, 6, 9, 12
If we want to exclude 0, we can change te filter() to:
let res = collection.filter(c => c.value > 0 && c.value % 3 === 0).map(o => o.value);
You can use filter method to filter out objects containing number divisible by 3, using modulo (%) operator. I have used map as well, to create an array of values, instead of objects.
const collection = [
{ text: "0", value: 0 },
{ text: "1", value: 1 },
{ text: "2", value: 2 },
{ text: "3", value: 3 },
{ text: "4", value: 4 },
{ text: "5", value: 5 },
{ text: "6", value: 6 },
{ text: "7", value: 7 },
{ text: "8", value: 8 },
{ text: "9", value: 9 },
{ text: "10", value: 10 },
{ text: "11", value: 11 },
{ text: "12", value: 12 },
];
let divby3 = collection.filter((x)=>x.value % 3 === 0).map((x)=>x.value)
console.log(`There are ${divby3.length} divisible numbers by 3: ${divby3}`)