我正在尋找一種從特定屬性具有唯一值的物件陣列中選擇隨機物件的方法。
例子:
const array = [
{
name:'foo',
message: 'hello'
},
{
name:'foo',
message: 'world'
},
{
name:'bar',
message: 'hello'
},
{
name:'bar',
message: 'world'
},
]
function theMagicMethod(elementsCount, specificUniqueProperty){
// ...
};
console.log(theMagicMethod(2, name));
// Expected output: [{name:'foo', message:'hello'},{name:'bar', message:'hello'}]
// or [{name:'foo', message:'hello'},{name:'bar', message:'world'}]
// etc...
// BUT NEVER WANT: [{name:'foo', message:'hello'},{name:'foo', message:'world'}]
我嘗試使用 do ... while 或 while ... 但是當我有條件地將一個元素添加到我的結果陣列時它總是崩潰。:
let items = [];
do{
let item = array[Math.floor(Math.random()*array.length)];
let found = false;
for(var i = 0; i < vendors.length; i ) {
if (vendors[i].Name == 'Magenic') {
found = true;
break;
}
}
if(!found){
items.push(item)
}
} while (items.length < 3)
uj5u.com熱心網友回復:
混洗物件,使用集合過濾唯一值,回傳前 N 個...
// fy shuffle, thanks to https://stackoverflow.com/a/2450976/294949
function shuffle(array) {
let currentIndex = array.length, randomIndex;
while (currentIndex != 0) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--;
[array[currentIndex], array[randomIndex]] = [
array[randomIndex], array[currentIndex]];
}
return array;
}
function theMagicMethod(elementsCount, specificUniqueProperty) {
let shuffled = shuffle(array.slice());
let uniqueValues = new Set()
let unique = shuffled.filter(el => {
const value = el[specificUniqueProperty];
const keep = !uniqueValues.has(value)
uniqueValues.add(value);
return keep;
})
return unique.slice(0, elementsCount);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/377989.html
標籤:javascript 数组
