Home > database >  Merge array in one array index? Javascript
Merge array in one array index? Javascript

Time:05-20

Right now I need to merge the string into one.

This is my try ->

newState((oldData) => [...oldData, newData.map((new) => new)]);

After this merge i got example of array ->

[ 
 [{id: 1, name: "One"}],
 [{id: 2, name : "two"}]
]

problem is newData because always print new array.

I need to data be like ->

[ 
 {id: 1, name: "One"},
 {id: 2, name : "two"}
]

What i am try, with foreEach ->

newState((oldData) => [...oldData, newData.forEach((new) => new)]);

No work.

Also what I am try

 let filteredArray = newData.map(data => data);
 newState((oldData) => [...oldData, filteredArray]);

Also no work, why?

Every time I get new information inside array newData....

I need solution to get only result inside array and print to

newState((oldData) => [...oldData, newResultWhichIsObject]);

Also some time my newData have few object inside array

CodePudding user response:

The map method isn't the right method to use in your case. Map method will take as an entry an array of n elements and mutate it into an array of n element, on which an operation was applied. See MDN documentation

You should use the reduce method, which provides the ability to construct a brand new array from an empty one, here is the snippet :

const baseArray = [ 
 [{id: 1, name: "One"}],
 [{id: 2, name : "two"}]
];

const flattenedArray = baseArray.reduce((acc, curr) => ([...acc, ...curr]), []);

// For demo purpose, console.log
console.log(flattenedArray);

Reduce array method is a bit tricky, that is why I invite you to read the documentation carefully and play with it.

CodePudding user response:

You can use .flat() method. Try this

const newData = [ 
   [{id: 1, name: "One"}],
   [{id: 2, name : "two"}]
];
console.log(newData.flat())

  • Related