Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to join two arrays in a map function?

What I want is to join my arrays that I get from my map function.

I tried to do with reduce :

const onFinish = (values) => {
    values.fields.map((el, idx) => {           
      
      console.log({ ...el, index: idx }); // this `console.log` prints me one array after the other
    }).reduce((acc, x) => {console.log(acc,x)}); // I tried with `reduce` but it prints me null

Also tried to do with useState:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 const onFinish = (values) => {
    values.fields.map((el, idx) => {           
      if (myArray === null){
        setMyArray(() => {
          return { ...el, index: idx };
        });
      }
      else {
        setMyArray(() => {
           return {...myArray,...el, index: idx };
        });
      }
    });
      console.log(myArray) // at my first call to this const onFinish myArray is printed as [] and at the second it prints with the last object only
   };

Someone knows how to get these objects joined/merged ?

Sample data the way that it’s print:
enter image description here

How I want to be: enter image description here

>Solution :

Altghough it is still not very clear from the screenshots (always prefer to use text and not images for data/code), it looks like you want

const onFinish = (values) => {
  const updatedValues = values.fields.map((field, index) => ({...field, index}));
  console.log( updatedValues );
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading