Search code examples
reactjsarraysobjectduplicatesfrontend

How to remove duplicate array values in react class component


I have a react class component displaying array of objects. However, when i render to display the data i get duplicate data. How can i remove the duplicates.

Customer.js

    this.state = {
          customer:[
           { id: 1, createdAt: "2023-01-22T05:19:45.943Z" },
           { id: 1, createdAt: "2023-01-19T02:19:45.943Z" },
           { id: 2, createdAt: "2023-01-18T05:30:45.943Z" },
          ],
        };

    componentDidMount() {
      axios
        .get("http://localhost:4000/customer/show", {
          responseType: "json"
        })
        .then(response => {
          
          this.setState({ customer: response.data });
        });
    }

.....................................
  render() {
  return(
     {
        this.state.customer?.map((item) => {
            return (
            <div>
              <div key={ item.id }> Time of Visit: {moment(item.createdAt).format('hh:mm A')} 
              </div>
            </div>
            );
         })
     })}

Output

Time of Visit: 5:19 PM Time of Visit: 2:19 PM

Time of Visit: 5:30 PM Time of Visit: 5:30 PM

When i render the array of objects i get duplicate values. How can i change this code to display only unique values. Thanks in advance


Solution

  • This is the best way to filter out the repetitive value:

    const ids = demoArray.map((d) => d.id)
    const filteredResponse = demoArray.filter(
        ({ id }, index) => !ids.includes(id, index + 1)
    

    So with your code it should be like this:

    this.state = {
      customer:[
       { id: 1, createdAt: "2023-01-22T05:19:45.943Z" },
       { id: 1, createdAt: "2023-01-19T02:19:45.943Z" },
       { id: 2, createdAt: "2023-01-18T05:30:45.943Z" },
      ],
    };
    
    componentDidMount() {
    axios
    .get("http://localhost:4000/customer/show", {
      responseType: "json"
    })
    .then(response => {
      const ids = response.data.map((d) => d.id)
      const filteredResponse = response.data.filter(
    ({ id }, index) => !ids.includes(id, index + 1)
    )
      
      this.setState({ customer: filteredResponse });
    });
    }
    
    render() {
    return(
      {this.state.customer?.map((item) =>  (
        <div>
          <div key={ item.id }> Time of Visit: 
            {moment(item.createdAt).format('hh:mm A')} 
          </div>
        </div>
        )
     )
    )
    }