skip to Main Content

I want to use the useState to store the value of the combined arrays. I am now getting the one and two array however I cannot concat both array into one. And I want to store them in a useState as well for me to map it later on a table.

const [samp, setSamp] = useState([]);

useEffect(() => {
    // I am getting the values for this one.
    const one = referralCodes.map((data) => {
      console.log([data].join().split(","));
    })
    // I am getting the values for this one as well.
    const two = usedReferralCodes.map((data) => {
      console.log([data].join().split(","));
    })
    // and I want to concat both arrays and join them into one with single incrementing index value
    const combined = ([...one].concat([...two]))
    
    // this one prints
    console.log("one: ", one)
    // this one prints as well
    console.log("two: ", two)
    // this one returns undefined
    console.log("combined: ", combined)
    // I wanto get the combined Value and setState it so I can access it and display it on a table.
    setSamp(combined);
   
  });

2

Answers


  1. well you can use spread operator(...) as bellow

    let a = [{fname : 'foo'}]
    let b = [{lname : 'bar'}]
    let c = [...a, ...b] // output [{fname : 'foo'},{lname : 'bar'}]
    
    
    let a = ['foo']
    let b = ['bar','ab']
    let c = [...a, ...b] // output ["foo", "bar", "ab"]
    

    or when you map the arrays, push each in single array then at the end join both arrays.

    Login or Signup to reply.
  2. You don’t need brackets around the mapped arrays when doing a concat.

    const array1 = [1, 2];
    const array2 = [3];
    const result = array1.concat(array2); // Expect [1, 2, 3]
    

    I’m not sure of what data referralCodes & usedReferralCodes contain, but another way for your situation is to create an empty constant array. And for loop push the results
    Adapt the below logic to suite your need

    const result = [];
    
    // Use for...of instead of map and push result
    for (const data of referralCodes) {
       const tmp = [data].join().split(",")
       result.push(tmp);
    }
    for (const data of usedReferralCodes) {
       const tmp = [data].join().split(",")
       result.push(tmp);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search