I need to randomize only some elements of an array.
Array example:
let array = [ // index 0 { randomize: true, value: 'value_1' }, // index 1 { randomize: false, value: 'value_2' }, // index 2 { randomize: false, value: 'value_3' }, // index 3 { randomize: true, value: 'value_4' }, // index 4 { randomize: false, value: 'value_5' }, ] The array is dynamically created, so it can have a lot of elements with randomize: true on any position. I want to randomize only elements with randomize: true, and others should remain in their current positions. What is the best solution to do it?
EDIT:
Answers from @georg, @Nina Scholz, @TKoL and @Neveen Atik all works. I implemented @georg solution since it is the most elegant.
.randomize === truerandomize: trueand I don't know their positions. I will add that information in question.Math.floor(Math.random() * array.length)until the picked element'srandomizeistrue. Then you pick a second index using the same method. Then you swap the two elements. It doesn't matter how the array is created or what the positions are.