Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.3k views
in Technique[技术] by (71.8m points)

javascript - Array with random unique integer numbers (0 to array.length - 1)

This question is how to generate an array of all unique fixed integer numbers that the highest is equal to the length - 1 of the array.

An example of a result array: [3, 6, 4, 2, 1, 5, 0]

  • All unique
  • Random
  • Highest number is in the highest number of the index (6)

This one is not: [3, 16, 4, 22, 19039, 555, 0]


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

First populate a sequential array, then sort by returning a random result in the compareFunction.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

let arrLen?= 7, resArr = []
for(let i=0; i < arrLen; i++){
  resArr.push(i)
}

resArr.sort((a,b) => {
  let ranBool = Math.floor(Math.random() * 2)
  //returns 0 or -1, which either leaves the integers in place or sorts the second one before the first 
  return ranBool - 1
})

console.log(resArr)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...