1

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!

3
  • Is the expectation here that once you apply available.filter the elements in the available array will be mutated? Commented Feb 24, 2022 at 13:03
  • Try to collect the filtered array separately. And then, update using setAllArtists. Commented Feb 24, 2022 at 13:05
  • Something like so: setAllArtists(prev => (prev.map(({available, ...rest}) => ({rest, available: available.filter(d => ((new Date(d) >= (new Date()))))}))));. Commented Feb 24, 2022 at 13:07

2 Answers 2

3

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()));
Sign up to request clarification or add additional context in comments.

Comments

0

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,
            }
        })
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.