Have you considered addressing the issue when assigning table values randomly? By implementing a simple protection measure, you can prevent assigning the same name more than 6 times:
let counts = [[1, 6], [2, 6], [3, 6], [4, 6]];
data.forEach( obj => {
let i = Math.floor(Math.random() * counts.length);
obj.table = 'table' + counts[i][0];
if(--counts[i][1] == 0) counts.splice(i, 1);
});
const data = [{
name: "",
pref: "",
table: ""
},{
name: "",
pref: "",
table: ""
}, ... (additional data objects included) ...];
let counts = [[1, 6], [2, 6], [3, 6], [4, 6]];
data.forEach( obj => {
let i = Math.floor(Math.random() * counts.length);
obj.table = 'table' + counts[i][0];
if(--counts[i][1] == 0) counts.splice(i, 1);
});
console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }
If you have already assigned table values randomly and need to re-assign them due to exceeding the limit of 6 occurrences for the same value, you could use this approach:
let counts = [6, 6, 6, 6];
let tables = [1, 2, 3, 4];
data.forEach( obj => {
let i = obj.table.slice(-1) - 1;
if (counts[i]) { // It's OK
counts[i]--;
return;
}
let j = Math.floor(Math.random() * tables.length);
i = tables[j];
obj.table = 'table' + i;
counts[i]--;
if (!counts[i]) tables.splice(j, 1);
});
The scenario begins with data containing an excess of table3
values:
var data = [{
name: "",
pref: "",
table: "table3"
},{
name: "",
pref: "",
table: "table1"
}, ... (additional data objects included) ...];
let counts = [6, 6, 6, 6];
let tables = [1, 2, 3, 4];
data.forEach( obj => {
let i = obj.table.slice(-1) - 1;
if (counts[i]) { // It's OK
counts[i]--;
return;
}
let j = Math.floor(Math.random() * tables.length);
i = tables[j];
obj.table = 'table' + i;
counts[i]--;
if (!counts[i]) tables.splice(j, 1);
});
console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }