how to select a random element from an array and increment the selected element by 1 like A = [0,0,0,0,0,0] and save it unless the browser is refresh

Viewed 58

A =[0,0,0,0,0] if I select 1 element and increment it by 1, so the should that to become new array A=[0,0,1,0,0] and when I also select another element and increment it then the new array may become A=[0,1,1,0,0] and so on. the increment is done by button, the increment may not only be 1 times. in short is to make a counter for each of the random selected element and update the array anytime

1 Answers

Your question is rather an JS question than an react-native.

Below is an sample:

let numbers = [0,0,0,0,0]
const max = numbers.length

function replaceArrayElement (values, index) {
  return  ([...values.slice(0, index), values[index]+1, ...values.slice(index+1)])
}

function getRandomInt() {
  return Math.floor(Math.random() * max);
}
 
 
for(var i = 0; i<=10; i++){
  numbers = replaceArrayElement(numbers, getRandomInt())
}

console.log('numbers: ',numbers)

Related