Øyvind Olsen
Øyvind Olsen

Reputation: 25

Remove specific values from an array

I'm in the process of making a code that prints all numbers divisable by 3 using an array, but im having trouble removing specific values. All the values i want prints correctly, but what i want is to exclude the numbers 27, 33, 300, 450, even tough they are correct.

ive tried messing with the splice function, and i know i can restructure the code without using arrays alltogheter. but i really want to use arrays to get a better understanding of what i can do with them.

<script>

    var div = division(1000);
    var j=0;
    function division(num){
        var threes = [];
    for (var i = 1; i <num; i++) {
        j=i%3
        if (j===0) {
        threes.push(i);
            }
        }
        return threes;
    }
    document.write(div);

</script>

this code correctly prints all the values between 1 and 1000 divisable by 3, but ive yet to find a good method to remove the above specified values.

Upvotes: 2

Views: 45

Answers (2)

Obsidian Age
Obsidian Age

Reputation: 42374

You simply want to set up an array containing the values you want to exclude, and then ensure that i is not in this array. This can be done with ![27, 33, 300, 450].includes(i), as is seen in the following:

var div = division(1000);
var j = 0;

function division(num) {
  var threes = [];
  for (var i = 1; i < num; i++) {
    j = i % 3
    if (j === 0 && ![27, 33, 300, 450].includes(i)) {
      threes.push(i);
    }
  }
  return threes;
}
document.write(div);

Upvotes: 3

Kamil Kiełczewski
Kamil Kiełczewski

Reputation: 92677

Try this

div.filter(x=>![27, 33, 300, 450].includes(x))

var div = division(1000);
    var j=0;
    function division(num){
        var threes = [];
    for (var i = 1; i <num; i++) {
        j=i%3
        if (j===0) {
        threes.push(i);
            }
        }
        return threes;
    }

    div = div.filter(x=>![27, 33, 300, 450].includes(x));

    document.write(div);

Upvotes: 3

Related Questions