screen_rotation
Copied to Clipboard
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.min.js"></script> </head> <body> <div id="app"></div> <script type="text/babel"> const { useState } = React; const App = () => { const [array1, setArray1] = useState([ { id: 1, name: 'computer' }, { id: 2, name: 'Laptop' }, { id: 3, name: 'Mobile' }, { id: 4, name: 'Tablet' }, { id: 5, name: 'Smartwatch' }, { id: 6, name: 'Television' }, { id: 7, name: 'Headphones' }, { id: 8, name: 'Camera' }, { id: 9, name: 'Game Console' }, ]); const [array2, setArray2] = useState([ { id: 4, name: 'Tablet' }, { id: 5, name: 'Smartwatch' }, { id: 7, name: 'Headphones' }, { id: 8, name: 'Camera' }, ]); const [resultArray, setResultArray] = useState([]); function compareAndRemove() { const updatedArray = [...array1]; array2.forEach(item => { const index = updatedArray.findIndex(obj => obj.id === item.id); if (index !== -1) { updatedArray.splice(index, 1); } }); setResultArray(updatedArray); } return ( <div className='container'> <h1>React Js compare two arrays and remove object by object id</h1> <h2>Array 1</h2> <ul> {array1.map(item => ( <li key={item.id}>{item.id} - {item.name}</li> ))} </ul> <h2>Array 2</h2> <ul> {array2.map(item => ( <li key={item.id}> {item.id} - {item.name}</li> ))} </ul> <button onClick={compareAndRemove}>Compare and Remove</button> <h2>Result Array</h2> <ul> {resultArray.map(item => ( <li key={item.id}>{item.id} - {item.name}</li> ))} </ul> </div> ); } ReactDOM.render(<App />, document.getElementById('app')); </script> <style> .container { border-radius: 8px; box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.1); padding: 20px; margin: 20px auto; max-width: 600px; text-align: center; } </style> </body> </html>