How to retrieve a random element from an array within a for loop using Angular 2

I'm in the process of developing a soundboard that will play a random sound each time a button is clicked. To achieve this, I have created an array within a for loop to extract the links to mp3 files (filename), and when a user clicks the button, the filename is changed using Math.floor(Math.random()).

However, I have encountered an issue where it continues to play the same sound instead of choosing from a random selection.

soundboard.ts

    /* Loop through the links and store their titles and sound file paths */
          for(let link of links) {
            let filename = link.getAttribute("href")            
            let rand = [filename];
            this.sounds.push({
              file: filename,
              rand: rand
            });
          }

    /* Function to play the sound */
         play(sound) {     
           sound.rand = sound.file[Math.floor(Math.random() * sound.file.length)];
           console.log(sound.rand)   
           this.media = new Audio(sound.rand);
           this.media.load();
           this.media.play();
         }

Answer №1

Upon analyzing the issue, it appears that there may be a logic error present. Based on the details provided in your problem statement, it seems like you are looking for something along the lines of:

export class Component {
  soundFileNames: string[] = [];

  media?: Audio;

  ngOnInit() {
    for (const link of links) {
      const fileName = link.getAttribute("href");
      soundFileNames.push(fileName);    
    }
  }

  playRandomSoundFile() {
    const randomIndex = Math.floor(Math.random() * soundFileNames.length);
    const randomFileName = soundFileNames[randomIndex];
    console.log(randomFileName);
    const audio = new Audio(randomFileName);
    audio.load();
    audio.play();
    this.media = audio;
  }
}

Answer №2

When it comes to handling common functionalities, utilizing the "underscorejs" library is usually the way to go. In your specific scenario of needing to retrieve a random value from an array, you can easily accomplish that using "underscorejs".

import * as _ from 'underscore';

getRandomElementFromArray (sounds) {
    let randomNumber = _.random(0, sounds.length);
    return sounds[randomNumber];
}

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

Track and monitor data modifications in Vue.js

I recently incorporated a Bootstrap Vue Table into my application and wanted to monitor user activity as they navigate through the pages using the pagination feature. Here is where you can find more information on the Bootstrap Vue Table To achieve this, ...

Contrasting actions observed when employing drag functionality with arrays of numbers versus arrays of objects

Being a newcomer to D3 and JavaScript, I'm hoping someone can help me clarify this simple point. I am creating a scatter graph with draggable points using code that closely resembles the solution provided in this Stack Overflow question. When I const ...

Navigate to Angular Link using Scope Data

I have the user's GPS location, which is not fixed. From the frontend, I need to open it as a Google Maps link. <a href="#" ng-click='window.open("https://www.google.com/maps/place/{{data.usergps}}", "_system", "location=yes"); return false;& ...

The splash screen fails to show up when I launch my Next.js progressive web app on iOS devices

Whenever I try to launch my app, the splash screen doesn't show up properly. Instead, I only see a white screen. I attempted to fix this issue by modifying the Next Metadata object multiple times and rebuilding the PWA app with no success. appleWebApp ...

Persistent hover effect for collapsible accordion panels when closing them

My simple accordion features a functionality where a class of .open is added to the title + content group when you open a panel for styling purposes. Everything works smoothly, but I've noticed on my phone that after clicking to close a panel, the hov ...

The component is not being activated by the subject subscribe

I'm having trouble subscribing to the Subject folder_id in the board component when passing the id from the files component. The boardId function is called when a button is pressed in the files component. The activateId is retrieved from the URL snap ...

Unraveling the Mystery of jQuery AJAX Response: Where Have I Gone Astray?

$.ajax({ type: 'POST', url: 'place/add', data: { lat: 45.6789, lng: -123.4567, name: "New Place", address: "123 Main St", phone: "555-1234", review: "Great place!", cat ...

What is the best way to navigate through images only when hovering?

I have a website that showcases a collection of images in a creative mosaic layout. Upon page load, I assign an array of image links to each image div using data attributes. This means that every image in the mosaic has an associated array of image links. ...

Instructions on utilizing sockets for transmitting data from javascript to python

How can I establish communication between my Node.js code and Python using sockets? In a nutshell, here is what I am looking for: Node.js: sendInformation(information) Python: receiveInformation() sendNewInformation() Node.js: receiveNewInformation( ...

It is not possible to recycle a TinyMCE editor that is embedded in a popup

Having a frustrating issue with the TinyMCE Editor plugin embedded within a Fancybox pop-up window. I have a list of objects with Edit links that trigger an AJAX call to retrieve content from the server and place it in a <textarea>. A TinyMCE editor ...

Does the user need to download the scripts from Google API multiple times during the insertion process?

Concerned about the potential need for multiple downloads of a script from an unknown location on the user's computer, I would like to explore options to mitigate this issue. Specifically, I am considering creating a condition to check the download st ...

Using typescript for Gnome shell extension development. Guidelines on importing .ts files

I'm currently working on a gnome shell extension using typescript, but I've encountered issues when trying to import .ts files. The Gnome shell documentation suggests configuring the tsconfig file as outlined in this Gnome typescript docs: { &q ...

Is there a way to send both a file and JSON data in a single HTTP request?

Once I developed a small application using NestJs where I implemented a BFF (Backend for Frontend) service. Within this service, I tried to execute a POST request to create a new user while also including the user's avatar in the same request. Here is ...

Personalized modify and remove elements on a row of the DataGrid material-ui version 5 component when hovered over

In my React Js app, I am utilizing Material UI components or MUI v5 as the UI library for my project. Within the DataGrid/DataGridPro component, I am implementing a custom edit and delete row feature. The requirement is to display edit and delete icons w ...

Angular 5 with Typescript encountered a failure in webpack due to the absence of the property "data" on the Response

I am encountering an issue during webpack compilation. It compiles successfully if I remove .data, but then the page crashes with calls from template->component (which in turn calls a service). Here is the error I am facing: ERROR in src/app/components ...

How to extract the value of a key from JSON using JavaScript

Need help with an API call to retrieve a list of subcategories? Here's an example of the JSON format: { "description": "Flower", "name": "Flower", "parent_id": "1" }, { "description": "Moon", "n ...

Imitating elegant angular input styles

Just before launch, the higher-ups have decided that they prefer a modern aesthetic for input controls - underlines rather than boxes, with labels that slide out of the way when the input is in focus. Check out the effect on this page: https://material.an ...

What is the best way to transfer information from a layout to its children within the app directory of Next.js?

One scenario I encounter frequently is the need for a button in a layout to toggle something within the components it contains. For instance, you might have a notifications button in a fixed layout that triggers a side panel to open in the main application ...

What is the best approach to merging multiple arrays to create a new array in CodeIgniter?

Here are two arrays provided below, where I want to combine the first key of the first array with the second key of the second array to create a new array. [animals1] => Array ( [0] => Horse [1] => Dog1 ...

Angular2 component testing in progress

Currently, I am facing the challenge of creating unit tests for a Angular2 website. Specifically, I am unsure of how to approach testing components using traditional Unit testing methods. One such component that I would like to test is as follows: import ...