Skip to content
Advertisement

how to iterate until the second last element in ReactJS

I am relatively new at ReactJS. So, I’ve been trying to create a countdown using React, which I managed to do, but it returns this

Essentially, I don’t want the colon after the ‘seconds’.

This is my code for the countdown.

const calculateTimeLeft = () => {
        let year = new Date().getFullYear();
        const difference = +new Date(`${year}-02-21`) - +new Date();
        let timeLeft = {};

        if (difference > 0) {
            timeLeft = {
                days: Math.floor(difference / (1000 * 60 * 60 * 24)),
                hours: Math.floor((difference / (1000 * 60 * 60)) % 24),
                minutes: Math.floor((difference / 1000 / 60) % 60),
                seconds: Math.floor((difference / 1000) % 60),
            };
        }
        return timeLeft;
    };
    const [timeLeft, setTimeLeft] = useState(calculateTimeLeft());
    const [year] = useState(new Date().getFullYear());

    useEffect(() => {
        setTimeout(() => {
            setTimeLeft(calculateTimeLeft());
        }, 1000);
    });

    const timerComponents = [];

    Object.keys(timeLeft).forEach((interval) => {
        if (!timeLeft[interval]) {
            return;
        }
        timerComponents.push(
            <span>{timeLeft[interval]}{" : "}</span>
        );
    });

Would really appreciate the help thanks!

Advertisement

Answer

const keyCount = Object.keys(timeLeft).length;

Object.keys(timeLeft).forEach((interval, index) => {  // Here, I added index
        if (!timeLeft[interval]) {
            return;
        }
        timerComponents.push(
            <span>
                {timeLeft[interval]}
                {index === (keyCount-2) ? '' : ' : '} // Here
            </span>
        );
    });
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement