Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array function that generates array with subset range of numbers

I am trying to create a function that builds an array up to a number set by the function parameter, with an if condition on being included based on whether the remainder is zero. The last number in the array should be no higher than the parameter. Here's what I came up with so far --

function justThreesUpTo(num) {  
var array = [];
array.length = num; 
for (i = 1; i < array.length; i++) {
  if(i % 3 === 0){
    array.push(i);
  }
    else i;
  }
  array.splice(0, num);
  return array;
}

When I console log this, with justThreesUpTo(20), I get --

// [ 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42 ]

I see the issue being setting the limiter at array.length, which maxes out the number of items that can be in the array, but I can't figure out what else to call to make sure the last number in the array goes no higher than the "num" parameter specified by the function call. Any ideas?

like image 694
davedub Avatar asked Jan 25 '26 13:01

davedub


1 Answers

Setting an array's length to something before the array is populated isn't a great idea - better to just iterate over the num itself. For example

for (var i = 1; i < num; i++) {
  // push to array if i % 3 === 0

Your else i won't do anything - you can just leave it off completely.

You could make your code a whole lot shorter and cleaner if you wanted:

function justThreesUpTo(num) {
  const length = Math.floor(num / 3);
  return Array.from({ length }, (_, i) => (i + 1) * 3);
}
console.log(justThreesUpTo(20));
like image 196
CertainPerformance Avatar answered Jan 27 '26 03:01

CertainPerformance



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!