I have an object containing array of blobs (represented as strings here!) and a pictureIndex
like this:
const data = {
pictures: ['blob1','blob2','blob3'],
pictureIndex: 0
}
shuffleArray(data.pictures);
Note: pictureIndex
is the index of 'blob1'
I want to shuffle the blobs inside pictures array to have a new random arrangement of the blobs but I want to get the index of blob1
at the final shuffled array. So if shuffled data is this:
['blob2','blob3','blob1']
I want to return 2 as pictureIndex
of 'blob1'...
So far I can shuffle the pictures easily like this without any idea how to modify the pictureIndex
:
const data = {
pictures: ['blob1','blob2','blob3'],
pictureIndex: 0
}
shuffleArray(data.pictures);
function shuffleArray(array) {
let currentIndex = array.length, randomIndex;
while (0 !== currentIndex) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--;
[array[currentIndex], array[randomIndex]] = [array[randomIndex], array[currentIndex]];
}
return array;
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
One way would be to make the shuffle function, accept the full object, then return the full object with the shuffled array and updated index.
It would then save you from needing to find the index again from the shuffled array.
let data = {
pictures: ['blob1', 'blob2', 'blob3'],
pictureIndex: 0
}
data = shufflePictures(data);
console.log(data)
function shufflePictures(data) {
let currentIndex = data.pictures.length,
randomIndex;
while (0 !== currentIndex) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--;
[data.pictures[currentIndex], data.pictures[randomIndex]] = [data.pictures[randomIndex], data.pictures[currentIndex]];
if (randomIndex === data.pictureIndex) {
data.pictureIndex = currentIndex
}
}
return data
}
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>