-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?

Azametzin
  • 5,223
  • 12
  • 28
  • 46
Olawale Oladiran
  • 561
  • 2
  • 11
  • 19
  • 1
    Possible duplicate of [How to filter an array from all elements of another array](https://stackoverflow.com/questions/34901593/how-to-filter-an-array-from-all-elements-of-another-array) – Dexygen Mar 18 '20 at 11:46

2 Answers2

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.

Delphi1024
  • 183
  • 1
  • 4
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)

Kai Salmon
  • 338
  • 1
  • 2
  • 9