Select three random items from a string array list along with their corresponding indexes using TypeScript in Angular

Consider this example: I am working with a string array

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

The task at hand is to select three random elements from the grocery list above, ensuring no repetition and including their respective indexes.

Answer №1

Check out this handy script I put together for you, it's designed to make your life easier.

const items = [
  'apple',
  'banana',
  'orange',
  'grapes',
  'cherry',
  'kiwi',
  'lemon',
  'lime',
  'pear',
  'plum',
  'melon',
  'pineapple',
  'watermelon',
  'strawberry',
  'raspberry',
  'blueberry',
  'blackberry',
  'cranberry',
  'peach'
];
let tempItems = items;

let randomItems = [];
let randomItemsIndex = [];

for(let i=0; i<3; i++) {
  let randomIndex = Math.floor(Math.random() * tempItems.length);
  let index = items.findIndex(o => o === tempItems[randomIndex]);
  randomItemsIndex.push(index);
  randomItems.push(tempItems[randomIndex]); 
  tempItems = tempItems.filter(o => o !==  tempItems[randomIndex]);
}

console.log(randomItems, randomItemsIndex);

Answer №2

One way to achieve this is by following the code snippet below:

const shoppingList = [
  'milk',
  'spices',
  'vegetables',
  'fruit',
  'bread',
  'snacks',
  'oil',
  'butter',
  'sugar',
  'rice',
  'beans'
];

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

const listSize =  shoppingList.length;
const selectedItemsMap = new Map();

for (var j =0; j <3;) {
    const randomIndex = generateRandomIndex(listSize);
    if (!selectedItemsMap.has(randomIndex)) {
        selectedItemsMap.set(randomIndex, shoppingList[randomIndex]);
        j ++;
    }

}

console.log(selectedItemsMap);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular - Update a single property of the environment

Managing multiple client environments in my Angular application has been a smooth process. Each client has its own set of variables, and by using the configuration flag, I can easily switch between them: { name: client1, address: client 1 address, ... ple ...

Whenever Sinon.stub() is invoked, it provides a unique value each time

Below is the code that I am currently writing tests for: 'use strict'; var internals = {}; var _ = require('lodash'); module.exports = { initialize: function (query) { internals.query = query; }, createField: fu ...

Distilling the Essence of "Deity" in Handling Runtime Errors

Working with a client who has a unique "God" component for creating form fields can be quite challenging. The complexity arises from the fact that we are using material design for non-mobile platforms and Ionic for mobile platforms. This special component ...

Retrieve an item from a MongoDB database using Mongoose

It seems like a simple problem, but my brain is struggling to comprehend the issue at 2 AM. I'm working on creating a profile page that displays basic public information. My approach involves retrieving the user's username from MongoDB based on t ...

Select a different radio button to overwrite the currently checked one

I am facing a situation where I have two radio buttons. The default checked state is one of them, but I want to change that and make the other one checked by default instead. Here is the HTML code: <div class="gui-radio"> <input type="radio" v ...

The use of Ajax post results in the retrieval of multiple arrays containing objects that possess various values

I have a PHP file (ajax.php) that retrieves messages from a database and a JavaScript file (main.js) that sends an AJAX request to this PHP file. My goal is to create a table row in the JS file for each message returned by the PHP file. Main.js: functio ...

What is causing this JavaScript function to output '2'?

Recently, I came across an unusual JavaScript function: (function f(){ function f(){ return 1; } return f(); function f(){ return 2; } })(); To my surprise, it returns 2 instead of crashing the browsers as expected due to recursion. Curious ...

Jquery Droppable issue arising with dynamically added DIVs

I am facing a similar issue as described in this question and this one I am trying to implement drag-and-drop and resize functionality. It is working fine for static elements, but I encounter issues when adding dynamic divs. The resize property works prop ...

How can I use Angular2 to draw a square [input] number of times?

I need to create a specific number of squares within a container using Angular2. Can you please provide me with a straightforward example, preferably utilizing canvas? Currently, I have converted webpack starter for use with Angular: This is the code ins ...

Feed JSON data into a jQuery function using JavaScript

A rudimentary Google Apps Script Web App has been created with the sole purpose of displaying JSON data in an HTML drop-down list. The JSON file is stored in Google Drive. Code inspiration taken from: http://jsfiddle.net/manoj_admlab/Mta5b/3/ However, we ...

The action is not being added to the HTML when the click event is triggered

I'm developing a GIF generator, with the aim of generating clickable buttons that will dynamically add 10 gifs based on the search term to the page. Although the click event is triggering the console log, it's not adding divs with gif images and ...

Is there a way to retrieve all potential string literals from an Array<>?

Can something similar be achieved in TypeScript? const options: Array<'Option1' | 'Option2' | 'Option3'> = []; // specify all available options: 'Option1' | 'Option2' | 'Option3' as show ...

Tips on how to create a loop without using a collection in Angular 2

I have a specific quantity and I need to repeat an action that many times. for (var _i = 0; _i < length; _i++) I am trying to replicate this logic in the html template. If I use ngFor, I would typically require a collection, but in this case I only ha ...

The application is experiencing extended loading times during production

After deploying my Angular 2 app on Heroku, I've noticed that it's taking a long time to load. Is there a way to bundle everything up instead of having all the scripts and stylesheets scattered across my index.html file? <html> <head> ...

The "angular2-image-upload" npm package encountering a CORS issue

Using the angular2-image-upload library for uploading files has been a smooth process until recently. After upgrading from version 0.6.6 to 1.0.0-rc.1 to access new features in future, I encountered issues with image uploads. The errors I faced were: htt ...

AngularJs input field with a dynamic ng-model for real-time data binding

Currently facing an issue with my static template on the render page. <form name="AddArticle" ng-submit="addArticle()" class="form add-article"> <input type="text" value="first" init-from-form ng-model="article.text[0]" /> <input typ ...

What is the most effective method for integrating additional CSS/JS libraries into a GitHub repository?

I would like to integrate FontAwesome, Bulma, jquery, and jquery-ui into one of my Github repositories for the front-end section. Currently, I am including the JS files or CSS files from these projects in my own JS/CSS folders, but I believe there might ...

Mastering the art of styling with SASS

The introductory guide suggests: When it comes to integrating the Kendo UI theme into your project, there are numerous approaches available. One recommended method is utilizing Webpack along with its Sass loader, enabling the customization of the Kendo UI ...

When attempting to invoke the rest function, an error occurs stating that the dataService.init in Angular is not

Learning AngularJS has been my current focus. To practice, I have been working on a Quiz app tutorial. However, I encountered an issue when trying to call the rest function of a factory after injecting it into one of my controllers. The JSON data for this ...

The extent of the modal window (AngularJS directive)

I've been experimenting with a modal window feature using Angular UI Bootstrap. Within the parent controller, I've defined the following function: $scope.open = function () { var modalInstance = $modal.open({ templateUr ...