-1

I'm working on a game whereby the player selects 6 numbers between 1 - 36.
What I want to do is to make a new array that excludes the 6 selected numbers and the new array will be 30 in length.

Here is what I've done.
The first array generated:

var selectedBalls = [2, 8, 25, 13, 8, 5]; //take this as the selected balls for example
var totalBalls = [];

function getBallsReady(){
  for (var i = 1; i <= 36; i++) {
    totalBalls.push(i);
  }
}

Here is the code I tried to get the new array, but is not perfect yet because at least 1 or 2 number(s) from the selected 6 numbers is still always part of the new array.

function generateNewBalls() {
  let clonedTotalBalls = [...totalBalls];

  selectedBalls.map((ball) => {
    clonedTotalBalls.splice(ball, 1);
  })
}

What am I doing wrong?

1

2 Answers 2

4

It can be done like this

clonedTotalBalls = totalBalls.filter((element)=>!selectedBalls.includes(element))

The filter function takes a predicate that is run once on every element and returns a boolean value for each. In this case the predicate is whether or not the element is included in the selectedBalls array. Therefore, all elements which are included in the selectedBalls array will return false, while all other elements return true. filter also does not modify the original array, but instead creates a new one.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you! this worked too. I chose to pick this as the right answer because it showed me I don't have to clone the original array.
For what it's worth, this is a much better answer!
@KaiSalmon your answer solved my problem, this answer brings another solution. All the same. Thank you guys
1

splice removes an element at a particular index, not by a particular value. To achieve your desired result you should use:

function generateNewBalls() {
  let clonedTotalBalls = [...totalBalls];

  selectedBalls.map((ball) => {
    let indexToRemove = clonedTotalBalls.indexOf(ball)
    clonedTotalBalls.splice(indexToRemove, 1);
  })
}

(I also recommend you change the map to forEach which is best practise if your don't want to return a value, or look into using filter and indexOf. But that isn't really relevant to your question)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.