Skip to content Skip to sidebar Skip to footer

Compare Two Array's And Disable A Single Element If The Id's Are Equal

I have two array in the state and both have id's. if some array have the same value (In this case 8) I would like to disable all the buttons that have this equal value. The buttons

Solution 1:

It's not quite clear where in the app hierarchy that component is so I've attempted a bit of guess work. You're almost there by the looks of things. You just need to iterate over the buttons and create them.

function Button(props) {
  const { disabled, text } = props;
  return <button disabled={disabled}>{text}</button>;
}

// Buttons creates the buttons in the set
function Buttons() {

  const setOne = [2, 6, 8];
  const setTwo = [3, 8, 4];

  // Remove the duplicates from the combined sets
  const combined = [...new Set([...setOne, ...setTwo])];

  // Get your duplicate values
  const hasDuplicateValues = setOne.filter(item => setTwo.includes(item));
  
  // `map` over the combined buttons
  // If `hasDuplicateValues` includes the current button, disable it
  return combined.map((n) => (
    <Button
      text={n}
      disabled={hasDuplicateValues.includes(n) && 'disabled'}
    />
  ));

}

ReactDOM.render(<Buttons />, document.querySelector("#root"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"/>

Post a Comment for "Compare Two Array's And Disable A Single Element If The Id's Are Equal"