'Filtering an array inside an object inside an array in React

I'm trying to filter an array, which is inside an object, itself inside an array in React. But it still returns the full array. How could I fix this?

This is my code:

const [allArtists, setAllArtists] = useState([])

useEffect(() => {
    axios.get("url")
        .then((res) => {
            setAllArtists(res.data)
        })
        .catch((err) => console.log(err))
}, [])

for (let i = 0; i < allArtists.length; i++) {
    allArtists[i].available.filter((date) => new Date(date) >= new Date())
}

And the array:

[
    {
        "available": [
            "2022-05-26",
            "2022-04-21",
            "2022-05-16",
            "2022-09-16",
            "2022-06-21",
            "2022-08-19",
            "2022-11-14",
            "2022-08-20",
            "2022-09-29",
            "2022-03-22",
            "2022-11-02",
            "2022-05-03",
            "2022-11-07",
            "2022-01-11",
            "2022-01-12"
        ]
    },
    {
        "available": [
            "2022-09-09",
            "2022-08-03",
            "2022-01-20",
            "2022-09-04",
            "2022-07-17",
            "2022-04-07",
            "2022-08-17",
            "2022-06-19",
            "2022-04-12",
            "2022-05-27",
            "2022-03-12",
            "2022-02-5",
            "2022-04-18",
            "2022-01-19",
            "2022-05-10"
        ]
    }
]

I also tried to put the for loop inside another useEffect, but it wasn't working either...

Thanks for your answers!



Solution 1:[1]

You're not assigning your filtered results to anything.

Your loop could be changed to something like this:

const result = allArtists.map(({ available }) => available.filter((date) => new Date(date) >= new Date()));

Solution 2:[2]

Thanks for your answers, I could use it like this and it's working:

setAllArtists(
    res.data
        .map(({ available, ...artist }) => {
            return {
                available: available.filter(
                    date => new Date(date) >= new Date()
                ),
                artist,
            }
        })
)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jahilldev
Solution 2 JulSeb42