Home > database >  How to compare the 2 arrays and obtain unique value and set the value in state
How to compare the 2 arrays and obtain unique value and set the value in state

Time:12-29

I was trying to compare 2 different api calls from which i am able to make out 2 different arrays of ids , So i am trying to filter out the ids which already exist in array2 , and for the remaining ids i am trying to set the state , could anyone help me with it ?

code so far :

    const [ prevAdmins , setPrevAdmins ] = useState<any>([]);
    const [options, setOptions] = useState([{value: "", label: ""}]);

//API 1 CALL 
get_user_groups({bot_id:params.botid , group_id:params.userid}).then((res) => {
             setDetails(res?.data?.data[0]);
             setGroupName(res?.data?.data[0].name)
             let prevAdmins: any = [];
             res?.data?.data[0]?.join_details.map((prevJoinee , idx) => {
              prevAdmins.push(prevJoinee.user_id)
              setPrevAdmins(prevAdmins)
             })
           });

//OUTPUT FOR API 1 "prevAdmins": ['61dfcfb71f492f4f4f589e93', '61dedd23bd15322626dd7539']

//2nd API CALL : 
  get_followers({bot_id:params.botid}).then((res) => {
            if(res.data.data){
              let option: any = [];
              let allAdmins: any = [];
              res.data.data.map((admin, index) => {
                allAdmins.push(admin._id);
                if(!prevAdmins.includes(allAdmins)){
                  option.push({value: admin._id, label: admin.displayName})
                 }
                })
                setOptions(option);
            }
          })

//OUTPUT FOR API 2 : ['61dfd02a1f492f4f4f589f00', '61dfcfb71f492f4f4f589e93', '61dedd23bd15322626dd7539']

Now what i am trying is to exclude the ids which is already present in Array 1 and setOptions should store the ids which are not excluded.

Regards !

CodePudding user response:

use the spread operator to avoid duplicates

   setOptions([...prevAdmins, ...option]);

CodePudding user response:

If you want to get the unique values form your api calls, You can use Set instead of an array.

Please refer: https://www.javatpoint.com/typescript-set

CodePudding user response:

You can use spread operator to combine two arrays and then convert it to Set and make an array from that Set. It will be unique.

roughly you can do something similar to this approach.

let array1 = [1,2,4]
let array2 = [4,3,5,6]

let combinedArray = [...array1, ...array2]
let arraySet = new Set(combinedArray)
let uniqueArray = Array.from(arraySet)
console.log(uniqueArray)

spread operator will combine two arrays but it will have duplicate values too. when you convert it into Set, it will remove any duplicate values.

Then you can simply generate an array from that Set variable.

You can do this to make it short too.

let uniqueArray = Array.from(new Set([...array1, ...array2]))

after you have the unique array you can simply set state with the uniqueArray variable.

  • Related