I have an array made of several hashes. I would like to find the highest value for a specific key/value and print the name value for that hash. For example, I have a "student" array of hashes containing information to each student. I would like to find which student had the highest test score and print their name out. For the array below, "Kate Saunders" has the highest test score, so I would like to print out her name.
Any help or pointers were to start on this would be greatly appreciated. I have a hacky work around right now, but I know there's a better way. I'm new to Ruby and loving it, but stumped on this one. Thanks so much!!!
students = [
{
name: "Mary Jones",
test_score: 80,
sport: "soccer"
},
{
name: "Bob Kelly",
test_score: 95,
sport: "basketball"
}.
{
name: "Kate Saunders",
test_score: 99,
sport: "hockey"
},
{
name: "Pete Dunst",
test_score: 88,
sport: "football"
}
]
You can use max_bymethod
students = [ { name: "Mary Jones", test_score: 80, sport: "soccer" }, { name: "Bob Kelly", test_score: 95, sport: "basketball" }, { name: "Kate Saunders", test_score: 99, sport: "hockey" }, { name: "Pete Dunst", test_score: 88, sport: "football" } ]
students.max_by{|k| k[:test_score] }
#=> {:name=>"Kate Saunders", :test_score=>99, :sport=>"hockey"}
students.max_by{|k| k[:test_score] }[:name]
#=> "Kate Saunders"
students = [ { name: "Mary Jones", test_score: 80, sport: "soccer" },
{ name: "Bob Kelly", test_score: 95, sport: "basketball" },
{ name: "Kate Saunders", test_score: 99, sport: "hockey" },
{ name: "Pete Dunst", test_score: 88, sport: "football" },
{ name: "Ima Hogg", test_score: 99, sport: "darts" }
]
Determine the highest score ala #Bartek.
max_score = students.max_by { |h| h[:test_score] }[:test_score]
#=> 99
Then determine which student(s) had that score.
star_students = students.select { |h| h[:test_score] == max_score }.
map { |h| h[:name] }
#=> ["Kate Saunders", "Ima Hogg"]
puts star_students
# Kate Saunders
# Ima Hogg
Ima's father was James ("Big Jim") Hogg, governor of Texas between 1891 and 1895. That Ima had a sister named "Ura" (which I thought was fact) turns out to be urban legend.
Related
I have for example this array:
[
{
"name": "Daniel",
"points": 10,
},
{
"name": "Ana",
"points": 20
},
{
"name": "Daniel",
"points": 40
}
]
And i want delete one "Daniel" and points to the sum of all whit the same name like this:
[
{
"name": "Daniel",
"points": 50,
},
{
"name": "Ana",
"points": 20
}
]
How can i transform it?
I was trying whit two bucles:
for name in persons {
for name2 in persons {
if name == name2 {
//remove the duplicate one and sum his points
}
}
}
but maybe there is a way too much easier than this one
A possible solution is to group the array with Dictionary(grouping:by:) then mapValues to the sum of the points.
The resulting dictionary [<name>:<points>] can be remapped to Person instances
struct Person {
let name: String
let points: Int
}
let people = [
Person(name: "Daniel", points: 10),
Person(name: "Ana", points: 20),
Person(name: "Daniel", points: 40),
]
let result = Dictionary(grouping: people, by: \.name)
.mapValues{ $0.reduce(0, {$0 + $1.points})} // ["Daniel":50, "Ana":20]
.map(Person.init)
print(result) // [Person(name: "Daniel", points: 50), Person(name: "Ana", points: 20)]
I have fetched data from a JSON file.. But when I tried to fetch another data from it, am unable to do so as it is a nested array... I know the solution can arrive easily but this is the first time am trying to loop a JSON file.. so kindly give your inputs.
SampleData = {
"squadName": "Super hero squad",
"homeTown": "Metro City",
"formed": 2016,
"secretBase": "Super tower",
"active": true,
"members": [
{
"name": "Molecule Man",
"age": 29,
"secretIdentity": "Dan Jukes",
"powers": [
"Immortality",
"Turning tiny",
"Radiation blast"
]
},
{
"name": "Madame Uppercut",
"age": 39,
"secretIdentity": "Jane Wilson",
"powers": [
"Million tonne punch",
"Damage resistance",
"Superhuman reflexes"
]
},
{
"name": "Eternal Flame",
"age": 1000,
"secretIdentity": "Unknown",
"powers": [
"Immortality",
"Heat Immunity",
"Inferno",
"Teleportation",
"Interdimensional travel"
]
}
]
};
GetJsonData() {
console.log(this.SampleData["powers"]);
for (let i = 0; i < this.SampleData["powers"].length; i++) {
if (this.SampleData["powers"][i].Immortality) {
console.log(this.SampleData.powers[i]);
}
}
}
{name: "Molecule Man", age: 29, secretIdentity: "Dan Jukes", powers: Array(3)}
{name: "Eternal Flame", age: 1000, secretIdentity: "Unknown", powers: Array(3)}
Your code needs to follow the structure of the JSON data; in particular, these are all valid things you could print:
console.log(this.SampleData.squadName);
console.log(this.SampleData.homeTown);
console.log(this.SampleData.members[0].name);
console.log(this.SampleData.members[0].powers[0]);
If you wanted to loop through each member and print their info, that might look like this:
this.SampleData.members.forEach(member => {
let powerString = member.powers.join(', ');
console.log('Name: ' + member.name);
console.log('Age: ' + member.age);
console.log('Powers: ' + powerString);
});
I used a forEach, but you can also use a for (let i = loop.
Can anyone figure out why the legend is undefined?
here is a plunker https://plnkr.co/edit/uSbRpx5w7nHvGQ3OG3x2?p=preview
here is the code
$scope.chartData = {
data: [20, 20, 20, 20, 20, 20, 20],
labels: [
"Joe",
"Jason",
"Mark",
"Mike",
"Ryan",
"Sean",
"Stephanie"
],
series: ['Year 2016',]
};
i have made 2 examples. the top one works, the one below it doesn't
Any idea?
In charts the data-set must be an array of data, where the data in-turn is itself an array
i.e)data-set: [data_1, data_2, data_3], where data_1=[1,2,3,4,5]; data_2=[45,32,12,25,12];..
And the series represents the corresponds the data.
But here in your case the data-set is an array of numbers, which is why the legend becomes undefined.
$scope.chartData = {
data: [[20, 20, 20, 20, 20, 20, 20]],
labels: [
"Joe",
"Jason",
"Mark",
"Mike",
"Ryan",
"Sean",
"Stephanie"
],
series: ['Year 2016' ]
};
I have the following Array (no limit of deepness) :
[
{
name: "foo",
age: 12,
children: [{
name: "zoo",
age: 44
},
{
name: "taz",
age: 17,
children: [{
name: 'tof',
age: 23
},
{
name: 'tok',
age: 42
}
]
}
]
},
{
name: "bar",
age: 54
}
]
And I would like to collect all the different values of the key name, in this example the result would be:
(the order does not matter)
['foo', 'zoo', 'taz', 'tof', 'tok', 'bar']
with a function like
def func(my_array, "name")
Do you have any idea how I should code that function ?
Assuming you know the substructure is under :children:
def extract(sequence, key)
sequence.flat_map do |hash|
[hash[key], *extract(hash[:children] || [], key)]
end
end
Here's a way of doing it using case to differentiate between the various object types you'll encounter:
def find_names(object, key_name)
case (object)
when Array
object.flat_map do |e|
find_names(e, key_name)
end
when Hash
[ object[key_name] ] + find_names(object.values, key_name).compact
end
end
Heres a fast but brittle regex way of doing it
def find_nested(arr, key)
arr.to_s.scan(/#{key.to_sym}=>"([^"]+)/).flatten
end
def find_em(arr)
arr.each_with_object([]) do |h,a|
a << h[:name]
a.concat(find_em(h[:children])) if h.key?(:children)
end
end
find_em(arr)
#=> ["foo", "zoo", "taz", "tof", "tok", "bar"]
I am new to mongodb. I am doing simple application that uses this database. Here is my doctors collection structure:
{
_id: 1,
name: "David",
specialisation: "dentist",
description: "Super dentist",
treatments: [
{
_id: 0,
price: 2200
},
{
_id: 2,
price: 200
},
{
_id: 5,
price: 2500
},
{
_id: 8,
price: 3200
},
{
_id: 13,
price: 2050
}
],
hospitals: [1, 2, 8, 5, 20]
},
{
_id: 2,
name: "John",
specialisation: "dentist",
description: "Super dentist",
treatments: [
{
_id: 2,
price: 2500
}
],
hospitals: [1]
}
What I want to do, is to get the max value of a treatment with specified id of all doctors in collection. For example in this case if I want to check treatment with _id = 2 it should return 2500, as it is written in John's object.
Any help would be appreciated. Thanks.
Named ur collection as stack
try this
db.stack.aggregate([ {$project:{"treatments._id":1, "treatments.price":1}},
{$unwind:"$treatments"},{$match:{"treatments._id":2}},
{$sort:{"treatments.price":-1}}, {$limit:1} ]);
result: { "_id" : 2, "treatments" : { "_id" : 2, "price" : 2500 } }
ref: https://docs.mongodb.org/manual/reference/operator/aggregation/unwind/