Search code examples
javascriptarraysfunctionsplice

How to remove an element from an array after it's called only once?


When a random element is called from the videos array, it should be deleted without the index being empty and undefined afterwards. The problem is that splice_video(); keeps calling the same element twice, when it's supposed to delete the element from the array after being called only once. (Each element in the array is a function).

        function playNextVideo() {
            const videos = [showVideo1,showVideo2,showVideo3,showVideo4,showVideo5];
            const random_video = Math.floor(Math.random() * videos.length);
            const video = videos.splice(random_video, 1);
            const splice_video = video[0]();
            splice_video();
    }

Solution

  • Declare the array of functions outside, not inside, so that the removal of the function from the array is persistent.

    const videoFns = [showVideo1, showVideo2, showVideo3, showVideo4, showVideo5];
    function playNextVideo() {
        const randomIndex = Math.floor(Math.random() * videoFns.length);
        const [videoFn] = videoFns.splice(randomIndex, 1);
        videoFn();
    }
    

    Live demo:

    const videoFns = Array.from(
      { length: 5 },
      (_, i) => () => console.log('video ' + i)
    );
    function playNextVideo() {
        if (!videoFns.length) return;
        const randomIndex = Math.floor(Math.random() * videoFns.length);
        const [videoFn] = videoFns.splice(randomIndex, 1);
        videoFn();
    }
    document.querySelector('button').addEventListener('click', playNextVideo);
    <button>click</button>