Photo by Tolga Ulkan on Unsplash
In this article, we will learn about the five possible ways of overcoming the problem of joining two tables. Which I experimented with and used in my focus.
Two Arrays
const fruits = [
{
name: 'Apple',
color: 'Red',
calories: '52'
},
{
name: 'Grape',
color: 'Green',
calories: '67'
},
{
name: 'Pomegranate',
color: 'Dark Red',
calories: '83'
}
];
const veggies = [
{
name: 'Carrots',
color: 'Orange',
calories: '41'
},
{
name: 'Beets',
color: 'Red',
calories: '43'
}
];
1. Using concat
const fruitsandveggies = [].concat(fruits,veggies);
Note: It will return the new array with merged array objects.
const fruitsandveggies = fruits.concat(veggies);
Note: It will change the original array (first array) and merged the second array objects into the first one.
2. Using spread operator
const fruitsnveggies = [...fruits, ...veggies];
3. Using push
With spread
const fruitswithveggies = [...fruits];
fruitsandveggies.push(...veggies);
Note: In the following code examples, using the spread operator to copy an array.
With loop
const fruitswithveggies= [...fruits];
const veggiesItems = [...veggies];
veggiesItems.forEach(item=>
fruitswithveggies.push(item)
);
4. Using reduce
const fruitData = [...fruits];
const veggieData = [...veggies];
veggieData.reduce((item1, item2) => { item1.push(item2); return item1 }, fruitData)
5. Using index
Adding second array item one by one in the last index of the first array
const fruitsClone = [...fruits];
const veggieClone = [...veggies];
veggieClone.forEach(item => fruitsClone[fruitsClone.length] = item)
Click the link below to see the sample code work
It’s all about this article. My favorite methods in the above list are “spread operator” and “concat”, comment on your favorite and if other methods merge two arrays and suggestions on this article.