Array map function in react for ternary operator - reactjs

This is my array
var CountryList = [{ name: Canada, value: 1 },
{ name: USA, value: 2 }]
This is the operation I am using right now
var filterStr = nextProps.Country.value == "1" ? 'Canada' : 'USA';
Now I want to use the array CountryList in the above code using to check whether Canada or USA is selected. Is it done using map?
If it's USA I want to populate States of USA in another Dropdown. If it's Canada Then States of Canada. SO according to the Selection from this array I want to populate the States. I need to check the selected country . ie, I want to get the country name.
How to do that?

var states = {USA: [{name: 'A', value:1},..],Canada: []}
var country = CountryList.find(country => country.value == nextProps.Country.value).name;
if (states[county]){
this.setState({states: states[country], enabledStates: true});
}else{
this.setState({states: [], enabledStates: false});
}
Show the states based on the flag enabledState.

if you want an array of all countries that have the name USA for exemple, you can use filter like this :
CountryList.filter = country => country.value === 1 ;
or if want to check if USA for exemple exist in this array, you can use "find"

map is not the correct function to use over here.
You should use either find or filter function.
let country = CountryList.find((c) => (c.value === 1))
country = country && country.name

Related

iterating over nested hash ruby

people = {
"fruits" => {
kiwi: ["john","james","diana"],
apple: ["hibaq","nura","nadia"],
strawberry: ["hana", "valerie","india"] },
"sports" => {
rugby: ["john","james","diana"],
football: ["hibaq","nura","nadia"],
tennis: ["hana", "valerie","india"]
}
}
puts 'Enter what category to search'
category = gets.chomp
puts 'Enter what value to search for'
value = gets.chomp
people.select { |person| person[category] == value }
.each { |person| puts person["name"] }
Hi, I am new to ruby and trying to understand hashes a bit more. I want to ask the user for a category e.g "fruits" and then print the array of names that like the fruit. I am unsure how to iterate through the nested hash to access the information. Any guidance would be greatly appreciated. Thank you
Hi, I am new to ruby and trying to understand hashes a bit more. I want to ask the user for a category e.g "fruits" and then print the array of names that like the fruit. I am unsure how to iterate through the nested hash to access the information. Any guidance would be greatly appreciated. Thank you
The following should work for you.
Please note that I changed the nested hash structure to use Strings instead of Symbols in the inner hashes. Because gets returns already a string that makes it easier to get the data by the key (string) that the user entered.
people = {
"fruits" => {
"kiwi" => ["john","james","diana"],
"apple" => ["hibaq","nura","nadia"],
"strawberry" => ["hana", "valerie","india"]
},
"sports" => {
"rugby" => ["john","james","diana"],
"football" => ["hibaq","nura","nadia"],
"tennis" => ["hana", "valerie","india"]
}
}
puts 'Enter what category to search'
category = gets.chomp # when entered "sports"
puts 'Enter what value to search for'
value = gets.chomp # when entered "rudby"
p people.dig(category, value)
#=> ["john", "james", "diana"]
See Hash#dig. Other options to get data out of a Hash might be Hash#[] or Hash#fetch.
Firstly, you would make life simpler for yourself by using a consistent format when writing your hash people. I suggest
people = {
fruits: {
kiwi: ["john","james","diana"],
apple: ["hibaq","nura","nadia"],
strawberry: ["hana", "valerie","india"] },
sports: {
rugby: ["john","james","diana"],
football: ["hibaq","nura","nadia"],
tennis: ["hana", "valerie","india"]
}
}
Notice that I have written fruits: { ... rather than 'fruits' => { ... to be consistent with, for example, kiwi: [ ....
With this change we can write the following helper method which can be used for both the outer hash and the inner hashes.
def obtain_response(keys, type)
loop do
puts "Enter what #{type} to search for"
k = gets.chomp.to_sym
break k if keys.include?(k)
puts "There is no such #{type} '#{k}'. Please try again"
end
end
We may then write
category = obtain_response(people.keys, 'category')
value = obtain_response(people[category].keys, 'value')
p people[category][value]
Here is an example session.
category = obtain_response(people.keys, 'category')
Computer User
-------- ----
Enter what category to search for
colours
There is no such category 'colours'. Please try again
Enter what category to search for
sports
Now
category
#=> :sports
Next
value = obtain_response(people[category].keys, 'value')
Computer User
-------- ----
Enter what value to search for
darts
There is no such value 'darts'. Please try again
Enter what value to search for
football
Now
value
#=> :football
We may now display the desired array.
p people[category][value]
#=> ["hibaq", "nura", "nadia"]
One may of course employ more elaborate prompts, such as
Enter the category to search for ("fruits" or "sports")

find is returning only the first data of a date

find funtion is returning only first data row of array i want all rows in the array when logging nightbefore
{data.map((arr) => {
let filteredData6 = [];
var nightbefore = arr.find((o) => o.medicationTime === "night before food" );
nightbefore.Medicines.forEach((e) => {
filteredData6.push(e);
setmedicine6(filteredData6);
});
console.log(nightbefore);
arr is used to sort data by date and then i am finding all data with the medicationTime as given but only the first arry is being feched when i use find
full code i have given in codesandbox for refercence
https://codesandbox.io/s/weathered-bird-7ppy7?file=/src/App.js
Array.prototype.find is indeed only returning the first match of an array as mentioned in its documentation.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
In order to achieve your goal you'll have to use the filter prototype:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
the code will then be :
var nightbefore = arr.filter((o) => o.medicationTime === "night before food" );

Date sorting is not working in muidatatable

https://codesandbox.io/s/stupefied-volhard-jntyu?fontsize=14&hidenavigation=1&theme=dark
this is my codesand box code. on date column result is not showing correctly.
I think the problem with the sort behaviour is that you are trying to sort strings of dates where the year is the last element.
In case you could edit your data directly, try putting the year, the month and so on. Something like:
const data = [
...,
[
"Mason Ray",
"Computer Scientist",
"San Francisco",
39,
142000,
"2019-10-03"
]
Here is an example using date-fnslibrary to parse your input data.
A detail of how is done:
const data = [...].map(info =>
info.map((val, index) => {
const date = new Date(val)
return index === 5
? isValid(date)
? format(date, 'yyyy-MM-dd')
: val
: val
})
)

Infinite loop on JS for

My code stays in the second for forever, testing the same category every step and decrementing every time.
I have two arrays, one of them is called categoriesToUpdate and is a list of category ids (string values) for categories that I have to update, and the other is called categories, containing all the actual category data I'm working with.
I have to test if the id value for a category that I have to update is the same as the database and if it is, decrement the attribute position of its object and update the database. But it is infinitely decrementing the bank.
let newCategory;
let name;
let position;
for(let id of categoriesToUpdate) {
for(let cat of categories) {
if(id === cat.id) {
position = cat.category.category.lastPosition - 1;
name = cat.category.category.categoryName;
newCategory = {
category: {
categoryName: name,
lastPosition: position,
}
}
cRef.child(id).update(newCategory);
}
}
}
Examples of the two arrays:
categoriesToUpdate = ['-lGz4j77...', '-uEbKO3...', ...]
and
categories = [
{
category: {
category: {
categoryName: "name",
lastPosition: "number",
}
},
id: "category id";
},
{
...
}
]
it is difficult to explain how I get the arrays, but basically, categoriesToUpdate is an array of ids that I add to my logic, I have to do update in each of these categoriesand categories is an array that has all categories of the database, comes from Firebase.
let id of categoriesToUpdate. I'm assuming categoriesToUpdate is an array of Category objects. So id is actually a Category object. To compare it should be id.id === cat.id.
Also you can try filter instead of a second loop.
Something like
var matched = categories.filter(c => c.id === id.id)[0];
Then compare matched. Nested loops are hard to read, imo.

How to fetch "name" property from an array if i know its corresponding "id"

I have a simple array with id and name. If i know the id then how can i fetch the name, array is shown below:
var dataobj = [
{id:1,name:"Jessica"},
{id:2,name:"Tom"},
{id:3,name:"Will"}
];
i have the id for example 2 with me in a variable, how can i get the name which belongs to this id ?
I have clickedID=2 value in my slist.component.ts and i want to fetch its corresponding name, how can i do it ?
To log the name which belongs to the id 2, it's as simple as following :
let obj = dataobj.find(obj => obj.id === 2);
console.log(obj.name);
you can use es6 array syntax:
dataobj.find(el => el.id === 2)
output:
Object {id: 2, name: "Tom"}
You can use the array find method
const secondItem = dataObj.find(function (item){
return item.id === 2;
})
Then name can be accessed as
secondItem.name
You can do something more readable and reusable with a dynamic find
var dataobj = [
{id:1,name:"Jessica"},
{id:2,name:"Tom"},
{id:3,name:"Will"}
];
let getNameFromObjId = obj => id => obj.find(x=> x.id===id).name;
console.log(getNameFromObjId(dataobj)(2))

Resources