Remove duplicate elements from array in react js example; In this tutorial, you will learn how to remove duplicate object and elements from array in react js apps.
How To Remove Duplicate Value from Array in Reactjs
Here are steps to remove duplicate values or items from array:
Step 1 – Create React App
In this step, open your terminal and execute the following command on your terminal to create a new react app:
npx create-react-app my-react-app
To run the React app, execute the following command on your terminal:
npm start
Check out your React app on this URL: localhost:3000
Step 2 – Install React Bootstrap
In this step, execute the following command to install react boostrap library into your react app:
npm install bootstrap --save
Add bootstrap.min.css file in src/App.js
file:
import React, { Component } from 'react' import '../node_modules/bootstrap/dist/css/bootstrap.min.css'; function App() { return ( <div> <h2>How To Remove Duplicate Value from Array in React js</h2> </div> ); } export default App;
Step 3 – Create Array Component
In this step, create ArrayComponent.js file. So, visit the src directory of your react js app and create array component file named ArrayComponent.js. And add the following code into it:
import React from 'react' class ArrayComponent extends React.Component{ render(){ const depArray = [100,80, 70, 80, 90,100, 71, 80]; var newArray = []; var newArray = depArray.filter(function(elem, pos) { return depArray.indexOf(elem) == pos; }); return( {newArray} ); } } export default ArrayComponent;
Step 4 – Import Array Component in App.js
In this step, you need to add ArrayComponent.js file in src/App.js
file:
import React from 'react'; import '../node_modules/bootstrap/dist/css/bootstrap.min.css'; import ArrayComponent from './ArrayComponent' function App() { return ( <div className="App"> <ArrayComponent /> </div> ); } export default App;
Conclusion
Remove duplicate elements from array in react js example; In this tutorial, you have learned how to remove duplicate object and elements from array in react js apps.