How to Remove Duplicates from an Array in React?

Estimated read time 2 min read

In React, you can remove duplicates from an array using the Set object or the filter() method. Here’s an example of how to remove duplicates from an array in React:

Using Set:

import React, { useState } from "react";

function MyComponent() {
  const [myArray, setMyArray] = useState(["apple", "banana", "cherry", "banana"]);

  const uniqueArray = [...new Set(myArray)];

  return (
    <div>
      {uniqueArray.map((item) => (
        <p key={item}>{item}</p>
      ))}
    </div>
  );
}

In this example, we’re defining a state variable called myArray that contains an array of four strings, including a duplicate string (“banana”). We’re using the Set object to create a new set from the original array, which automatically removes duplicates. We’re then using the spread operator to convert the set back to an array.

Using filter():

import React, { useState } from "react";

function MyComponent() {
  const [myArray, setMyArray] = useState(["apple", "banana", "cherry", "banana"]);

  const uniqueArray = myArray.filter((item, index) => myArray.indexOf(item) === index);

  return (
    <div>
      {uniqueArray.map((item) => (
        <p key={item}>{item}</p>
      ))}
    </div>
  );
}

In this example, we’re defining a state variable called myArray that contains an array of four strings, including a duplicate string (“banana”). We’re using the filter() method to create a new array that includes only the first occurrence of each element. We’re passing a callback function to filter() that compares the index of the current item to the index of the first occurrence of the item in the array. If the indexes are the same, the item is included in the new array.

When the component is rendered, either of these methods will return a new array that contains only the unique elements of the original array. We’re then using the map() method to render a <p> element for each unique string in the array. Note that we’re using the key prop in the <p> element to help React optimize the rendering of the list.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply