merge and display array of object data in table using react js - arrays

I need to merge array1 and array2 , display in a table
array1= [ {id: 1,event:party, oldcity: Singapore}
{id: 2, event:fest,oldcity:Paris }]
array2= [ {id: 1,event:party, newcity: bombay}
{id: 2, event:fest,newcity:madras }]
output of merge array
mergearray= [ {id: 1,event:party,oldcity: Singapore,newcity: bombay}
{id: 2, event:fest,oldcity:Paris,newcity:madras }]
display mergearray in table
id event oldcity newcity
1 party singapore bombay
2 fest paris madras
if i merge the array
mergearray[{id: 1,event:party, oldcity: Singapore}
{id: 2, event:fest,oldcity:Paris }
{id: 1,event:party, newcity: bombay }
{id: 2, event:fest,newcity:madras }]
but am expecting to be like this
mergearray= [ {id: 1,event:party,oldcity: Singapore,newcity: bombay}
{id: 2, event:fest,oldcity:Paris,newcity:madras }]

How do you merge the arrays ?
const array1 = [{
id: 1,
event: 'party',
oldcity: 'Singapore'
}, {
id: 2,
event: 'fest',
oldcity: 'Paris'
}];
const array2 = [{
id: 1,
event: 'party',
newcity: 'bombay'
}, {
id: 2,
event: 'fest',
newcity: 'madras'
}];
// I would merge arrays this way
const mergedArray = [...array1, ...array2];
console.log('mergedArray: ', mergedArray);

Related

Check, if in .map (), that object exists in another array React

How can I see in the map of products if that product is in the favorites?
Log of products
[
{id: 1, product_name: “product one”},
{id: 2, product_name: “product two”},
{id: 3, product_name: “product three”}
]
Log of favorites
[
{id: 1, product_name: “product one”},
{id: 2, product_name: “product two”}
]
{products.map((item} =>
// Here, if the product is in the favorites list then show x else show y
// I need to check here if the product is in the favorites list, to show two different types of icons
)
I don’t know how to do, I also tried to map to favorites with product id = favorite product id, but it didn't work
var products = [{
id: 1,
product_name: 'product one'
},
{
id: 2,
product_name: 'product two'
},
{
id: 3,
product_name: 'product three'
}
]
var favorites = [{
id: 1,
product_name: 'product one'
},
{
id: 2,
product_name: 'product two'
}
]
const solution = products.map((product)=>{
return favorites.find(el=>el.product_name === product.product_name) ? 'x' : 'y'
})

How to Manage the response of the API in react?

i did a request to the API, then the response is as the following:
data1 = [{id: 1, code:1, title:title1}, {id:2, code:3, title:title2}, ...]
Now i would like to extract an array of the titles of the above response as below:
titles = [title1, title2, ....]
how can i do it by map?
And the second question:
Consider if the response would be as follow:
data2 = [{id: 1, code:1, title:title1, chapters:[{id:1, chapter: chapter1},{id:2, chapter: chapter2}, ...]}, {id:4, code:5, title:title3, chapters:[{id:4, chapter: chapter3}, ...]}, ...]
In this case how can i extract an array of the chapters as following:
chapters = [chapter1, chapter2, chapter3]
I tried to do them as below:
for the first question:
title = data1.map((item) => {item.title})
for the second one i did:
chapters = data2.chapters.map((item) => {item.chapter})
But it doesn't work. I think some where there are error in syntaxes.
Can any one help me how to manage these data?
Thank you.
Yep, you are wrong with syntax.
Firs case - title = data1.map((item) => {item.title})
You've wrapped item.title with {}, so you should add return. Or omit {}.
For example: title = data1.map(item => item.title)
Second case - same issue with {}, but you should also use flatMap because you need flat list in result. If you write with regular map - you won't get desired ["chapter1", "chapter2"].
See also detailed example below.
const data1 = [
{ id: 1, code: 1, title: "title1" },
{ id: 2, code: 3, title: "title2" }
];
const data1_mapped = data1.map(d => d.title);
console.log(data1_mapped);
const data2 = [
{
id: 1,
code: 1,
title: "title1",
chapters: [{ id: 1, chapter: "chapter1" }, { id: 2, chapter: "chapter2" }]
},
{
id: 2,
code: 2,
title: "title2",
chapters: [{ id: 1, chapter: "chapter22" }, { id: 2, chapter: "chapter32" }]
}
];
const data2_mapped = data2.flatMap(d => d.chapters.map(c => c.chapter));
console.log(data2_mapped);
You are not returning a value. Try removing braces like so...
title = data1.map((item) => item.title)
chapters = data2.chapters.map((item) => item.chapter)
See this for more info on the issue:
Meaning of curly braces in array.map()

Sort array based on the order from another array Swift

I have the following tow arrays:
fetchedProducts = [
[name: "productName20", id: 20],
[name: "productName3", id: 3],
[name: "productName1", id: 1]
]
sortedProducts = [
[productName1: "1"], // I know the numbers here are string; I need them to be string
[productName20: "20"],
[productName3: "3"]
]
Now I need to sort fetchedProducts based on the order of sortedProducts so it would end up looking like the following:
fetchedProducts = [
[name: "productName1", id: 1],
[name: "productName20", id: 20],
[name: "productName3", id: 3]
]
You can try the following in Swift. Note the dictionaries in Swift are unordered so you have to use arrays for ordered collections:
let fetchedProducts = [
(name: "productName20", id: 20),
(name: "productName3", id: 3),
(name: "productName1", id: 1),
]
let sortedProducts = [
("productName1", "1"),
("productName20", "20"),
("productName3", "3"),
]
let sortedFetchedProducts = sortedProducts
.compactMap { s in
fetchedProducts.first(where: { s.1 == String($0.id) })
}
print(sortedFetchedProducts)
// [(name: "productName1", id: 1), (name: "productName20", id: 20), (name: "productName3", id: 3)]
JavaScipt realisation:
const fetchedProducts = [
{name: "productName20", id: 20},
{name: "productName3", id: 3},
{name: "productName1", id: 1}
];
const sortedProducts = [
{productName1: "1"}, // I know the numbers here are string; I need them to be string
{productName20: "20"},
{productName3: "3"}
];
const sortProducts = (fetchedProducts, sortedProducts) => {
// Extract ordered id from the sortedProducts array
const orderIds = sortedProducts.map(sorted => +Object.values(sorted));
// Find product by sorted id and put into new array
const sortedFetchedProducts = [];
orderIds.forEach(id => {
let product = fetchedProducts.find(item => item.id === id);
sortedFetchedProducts.push(product);
});
return sortedFetchedProducts;
}
const sortedFetchedProducts = sortProducts(fetchedProducts, sortedProducts);
console.log(sortedFetchedProducts);
Output:
[
{ name: 'productName1', id: 1 },
{ name: 'productName20', id: 20 },
{ name: 'productName3', id: 3 }
]

How to filter multiple objects from a list objects by a property array?

I have a object array in which each object contain an id and a name and a separate array contains a set of ids. I want to filter first array based on the second array.
const data= [
{
id: 1,
name: 'name1'
},
{
id: 2,
name: 'name2'
},
{
id: 3,
name: 'name3'
},
{
id: 4,
name: 'name4'
}
];
const array = [1,3,4];
const expectedResult= [
{
id: 1,
name: 'name1'
},
{
id: 3,
name: 'name3'
},
{
id: 4,
name: 'name4'
}
];
Use .filter and .includes
const data= [
{
id: 1,
name: 'name1'
},
{
id: 2,
name: 'name2'
},
{
id: 3,
name: 'name3'
},
{
id: 4,
name: 'name4'
}
];
const array = [1, 3, 4]
const result = data.filter((item) => {
//gives us items that passes a condition
return array.includes(item.id)
})
console.log(result)

What is an example of normalizing the state in a React Redux app?

I'm reading the Redux Reducers docs and don't get how normalizing the state would work. The current state in the example is this:
{
visibilityFilter: 'SHOW_ALL',
todos: [
{
text: 'Consider using Redux',
completed: true,
},
{
text: 'Keep all state in a single tree',
completed: false
}
]
}
Can you provide an example of what the above would look like if we followed the below?
For
example, keeping todosById: { id -> todo } and todos: array inside
the state would be a better idea in a real app, but we’re keeping the
example simple.
This example is straight from Normalizr.
[{
id: 1,
title: 'Some Article',
author: {
id: 1,
name: 'Dan'
}
}, {
id: 2,
title: 'Other Article',
author: {
id: 1,
name: 'Dan'
}
}]
Can be normalized this way-
{
result: [1, 2],
entities: {
articles: {
1: {
id: 1,
title: 'Some Article',
author: 1
},
2: {
id: 2,
title: 'Other Article',
author: 1
}
},
users: {
1: {
id: 1,
name: 'Dan'
}
}
}
}
What's the advantage of normalization?
You get to extract the exact part of your state tree that you want.
For instance- You have an array of objects containing information about the articles. If you want to select a particular object from that array, you'll have to iterate through entire array. Worst case is that the desired object is not present in the array. To overcome this, we normalize the data.
To normalize the data, store the unique identifiers of each object in a separate array. Let's call that array as results.
result: [1, 2, 3 ..]
And transform the array of objects into an object with keys as the id(See the second snippet). Call that object as entities.
Ultimately, to access the object with id 1, simply do this- entities.articles["1"].
You can use normalizr for this.
Normalizr takes JSON and a schema and replaces nested entities with their IDs, gathering all entities in dictionaries.
For example,
[{
id: 1,
title: 'Some Article',
author: {
id: 1,
name: 'Dan'
}
}, {
id: 2,
title: 'Other Article',
author: {
id: 1,
name: 'Dan'
}
}]
can be normalized to
{
result: [1, 2],
entities: {
articles: {
1: {
id: 1,
title: 'Some Article',
author: 1
},
2: {
id: 2,
title: 'Other Article',
author: 1
}
},
users: {
1: {
id: 1,
name: 'Dan'
}
}
}
}

Resources