how to efficiently shuffle array of object looking something like this:
array = [
{from: "john", requestNum: 1},
{from: "jack", requestNum: 1},
{from: "jill", requestNum: 1},
{from: "john", requestNum: 2},
{from: "jane", requestNum: 1}]
I would like to shuffle these objects by random, but requests from same name must retain their relative order. So where ever Johns request number 2 ends up in shuffled array, it must be behind its request n1.
What I came up with and is functional, but probably really clumsy is:
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
console.log("SHUFFLED");
console.log(array);
const indexes = {};
for (let i = 0; i < array.length; i++) {
if (indexes[array[i].from]) {
indexes[array[i].from].push(i);
} else {
indexes[array[i].from] = [i];
}
}
const requests = {};
for (let i = 0; i < array.length; i++) {
if (requests[array[i].from]) {
requests[array[i].from].push(array[i]);
} else {
requests[array[i].from] = [array[i]];
}
}
function compare(a, b) {
if (a.requestNum < b.requestNum) {
return -1;
}
if (a.requestNum > b.requestNum) {
return 1;
}
return 0;
}
for (var key in requests) {
//console.log(requests[key]);
if (requests[key].length > 0) {
const sorted = requests[key].sort(compare);
// console.log(sorted);
requests[key] = sorted;
}
}
const sortedArray = [];
for (var key in indexes) {
for (let i = 0; i < indexes[key].length; i++) {
sortedArray[indexes[key][i]] = requests[key][i];
}
}
console.log("SORTED");
console.log(sortedArray);
Any ideas how to make it more efficient?