iwato 19 Posted November 2, 2018 Report Share Posted November 2, 2018 CONCERN: The following function does what it is suppose to do -- namely, select at random and without duplication a given number of elements from an array of elements. However, I fear that it is hopelessly awkward and would like your professional assessment of its construction. You will likely not find another like it on the internet, but parts of it were obtained therefrom. function selectCubes(gates) { function onlyUnique(value, index, self) { return self.indexOf(value) === index; } var cubes = ['cube_one', 'cube_two', 'cube_three', 'cube_four', 'cube_five', 'cube_six', 'cube_seven']; var selectedCubes = []; var filteredCubes = []; var n = 0; while (n < gates) { selectedCube = cubes[Math.floor(Math.random()*cubes.length)]; selectedCubes.push(selectedCube); if (filteredCubes.length < gates) { var filteredCubes = selectedCubes.filter(onlyUnique); n++; } } return filteredCubes; } console.log('selectCubes(3):' + selectCubes(3)); Please comment and have a great weekend! Roddy Quote Link to post Share on other sites
justsomeguy 1,135 Posted November 2, 2018 Report Share Posted November 2, 2018 You could replace that filter function with Array.splice. Generate the random number, use splice to remove and return the removed element, and then push the element onto the other array. function selectCubes(gates) { var cubes = ['cube_one', 'cube_two', 'cube_three', 'cube_four', 'cube_five', 'cube_six', 'cube_seven']; var selectedCubes = []; while (selectedCubes.length < gates) { selectedCubes.push(cubes.splice(Math.floor(Math.random()*cubes.length), 1)[0]); } return selectedCubes; } 1 Quote Link to post Share on other sites
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.