I have two arrays like below:-
const fruit = ['apple', 'pineapple', 'grapes'];
const price = ['100', '200', '150']
I want to create a material-table in ReactJs like this:-

const columns = [
{
title: "Fruits",
field: "fruits"
},
{
title: "Price",
field: "price"
}
];
I'm unable to make the data=[] using the above two arrays. Also, I have a constraint that it might happen that the arrays would be like as below:-
const fruit = [''];
const price = ['100', '200', '150'];
If this is so, then I only want to show the Price column with its data and vice versa. I tried making a data object like below:-
const data = {};
fruits.forEach((key, i) => (data[key] = price[i]));
but how do I map over this and create an array which I can pass to MaterialTable like this:-
<MaterialTable
columns={columns}
data={data}
options={{
paging: false,
search: false,
draggable: false
}}
/>
So you want your data to be merged together and generate new array of objects where keys are fruits and price. You can use map function in order to map over fruits array and generate new array of objects, like so:
const fruit = ['apple', 'pineapple', 'grapes'];
const price = ['100', '200', '150']
const merged = fruit.map((fruit, index) => ({ fruit, 'price': price[index] }))
console.log(merged)
EDIT
Right, so based on the comment, you want to generate an array that matches the longest array passed in. i.e. take the longest array (fruit or price) and generate new array from those values trying to match fruit and price. Perhaps something like this would work
const fruit = ['apple', 'pineapple', 'grapes'];
const price = ['100', '200', '150']
const mergeArrays = (fruits, prices) => {
const maxSize = Math.max(fruits.length, prices.length);
return Array.apply(null, Array(maxSize)).map((_, index) => {
const value = {}
if (fruits[index]) {
value.fruit = fruits[index]
}
if (prices[index]) {
value.price = prices[index]
}
return value
})
}
console.log(mergeArrays(fruit, price))
console.log(mergeArrays([], price))
console.log(mergeArrays(fruit, []))
In this example, we are first finding the longest array using Math.max function. Then we are creating new, empty array with the size of the max length and iterating over it. We can then check whether there is an item in fruits and prices array and if it is, we add it to the return value.