Home > Mobile >  how to compare two specific elements from two different Arrays in JavaScript
how to compare two specific elements from two different Arrays in JavaScript

Time:04-13

i have two states , state A and state B the first one contain an object witch is postuledby that contain the id of user and in state B i have the user id . so i wanna know how to compare postuledby with user id
this is my try but it did not work cause it give me all the users and didn't compare :

const PostuledBy = ({ offrr, dev }) => {
  const [listdev , setListdev]=useState([]);


useEffect(()=>{
setListdev(dev
  ?.filter((el, index) => {
    return offrr.postuledby.filter((ell) => ell._id === el._id);
  }))
},[])
return ()

CodePudding user response:

try this:

function compareByInnerId(AArray, BArray){
    return AArray.filter(el=>BArray.includes(el.id))
}

I didn't really got the whole postuledby naming thing but the code above expects the BArray to have only the ids. something like: [1,32,4] and AArray to have the whole object. ex: [{name:"blah", id:1}, {name:"mlah", id:32}]

CodePudding user response:

you have 2 arrays, one is ids for control and other containing objects.

const ids = ["1", "2", "7", "75"];

const objArr = [
    { id: "1", name: "mike" },
    { id: "3", name: "jesse" },
    { id: "75", name: "Den" },
    { id: "89", name: "Jen" }
  ];

with a simple filter you can find the objects containing in ids array:

const [result, setResult] = useState([]);

useEffect(() => {
    setResult(objArr.filter((obj) => ids.some((id) => id === obj.id)));
  }, []);

here is a simple example in codesandbox

  • Related