从字符串数组列表中选择三个随机元素及其在打字稿中的实际索引 Angular

pick three random elements from string array list with their actual indexes in typescript Angular

比如我有这个字符串数组

    const groceries = [
      'milk',
      'coriander',
      'cucumber',
      'eggplant',
      'carrot',
      'brinjal',
      'onions',
      'tomatoes',
      'soap',
      'bag',
      'pepper',
      'salt',
      'fruits',
      'bread',
      'pasta',
      'oil',
      'butter',
      'honey',
      'sugar'

    ];

我需要从上面的杂货列表中随机选择三个元素,不重复,并附上它们的索引。

我已经为您创建了这个简单的脚本,希望它能对您有所帮助

const groceries = [
  'milk',
  'coriander',
  'cucumber',
  'eggplant',
  'carrot',
  'brinjal',
  'onions',
  'tomatoes',
  'soap',
  'bag',
  'pepper',
  'salt',
  'fruits',
  'bread',
  'pasta',
  'oil',
  'butter',
  'honey',
  'sugar'
];
let tempGroceries = groceries;

let randomGroceries = [];
let randomGroceriesIndex = [];

for(let i=0; i<3; i++) {
  let randomIndex = Math.floor(Math.random() * tempGroceries.length);
  let index = groceries.findIndex(o => o === tempGroceries[randomIndex]);
  randomGroceriesIndex.push(index);
  randomGroceries.push(tempGroceries[randomIndex]); 
  tempGroceries = tempGroceries.filter(o => o !==  tempGroceries[randomIndex]);
}

console.log(randomGroceries, randomGroceriesIndex);

你可以这样做,

const groceries = [
  'milk',
  'coriander',
  'cucumber',
  'eggplant',
  'carrot',
  'brinjal',
  'onions',
  'tomatoes',
  'soap',
  'bag',
  'pepper',
  'salt',
  'fruits',
  'bread',
  'pasta',
  'oil',
  'butter',
  'honey',
  'sugar'
];

const random = (max: number) => {
    return Math.floor(Math.random() * max);
}

const size =  groceries.length;
const groceriesMap = new Map();

for (var i =0; i <3;) {
    const randomIndex = random(size);
    if (!groceriesMap.has(randomIndex)) {
        groceriesMap.set(randomIndex, groceries[randomIndex]);
        i ++;
    }

}

console.log(groceriesMap);