How to choose one data from an array without random - arrays

I want to ask about how I can select one data from the array, and choose another without using a random function?
{
no: 1,
id_pertanyaan: "9",
pertanyaan: "Alat indra yang paling peka untuk membedakan benda panas dan benda dingin adalah?",
point: "1",
pilA: "Hidung",
pilB: "Telinga",
pilC: "Kulit",
cabang: "IPA",
jawaban: "Kulit",
keterangan: "Alat indra yang paling peka untuk membedakan benda panas dan benda dingin adalah?"
},
{
no: 2,
id_pertanyaan: "11",
pertanyaan: "Zat hijau daun disebut juga dengan?",
point: "1",
pilA: "Floem",
pilB: "Klorofil",
pilC: "Xylem",
cabang: "IPA",
jawaban: "Klorofil",
keterangan: "Zat hijau daun disebut juga dengan?"
},
And this is my function
//console.log(this.state.gagec);
var item = this.state.pertanyaande[
Math.floor(Math.random() * this.state.pertanyaande.length)
];
this.setState(
{
id_pertanyaan: item.id_pertanyaan,
pertanyaan: item.pertanyaan,
point: item.point,
pilA: item.pilA,
pilB: item.pilB,
pilC: item.pilC,
jawaban: item.jawaban,
keterangan: item.keterangan,
},
() => {
this.setTimer();
}
);
The code above is I try to be able to get the array randomly, but it raises new problems because sometimes the same data appears, I want to display data from the array only one data (not all) in a way one by one, how to get the first data in my array, then I run the script again I get the second array data?

I just had to make it not random and change it to state so if id 1 is active then if the function rerun it'll get id 2 because state+1

Related

Cant figure out how to go through array in Swift and find specific data

Hello I have question about arrays.
I have an array with following data, also I have corresponding Struct for SpiritRelation():
var spiritRelations = [
SpiritRelation(relationName: "Thunder Lantern", relationSpirit1: "Razor", relationSpirit2: "Lamp Genie", relationSpirit3: "", relationSpirit4: "", relationStats: "Double resist +5%, ATK +1600", relationSpiritIcons: ["razor", "genie"]),
SpiritRelation(relationName: "Illusive Fantasy", relationSpirit1: "Heavenly Maiden", relationSpirit2: "Lamp Genie", relationSpirit3: "", relationSpirit4: "", relationStats: "Excellent strike +15%, Dmg Penetration +15%, Max HP +11500", relationSpiritIcons: ["maiden", "genie"]),
SpiritRelation(relationName: "Grand Demonlord Gathering", relationSpirit1: "Sand Golem", relationSpirit2: "Lamp Genie", relationSpirit3: "", relationSpirit4: "", relationStats: "Excellency Resist +20%, Double Dmg +5%, ATK +1600", relationSpiritIcons: ["golem", "genie"])
}
array which contains data which will be selected by user:
var selectedSpiritsForRelation = [String]()
array of type String because I put there values which corresponds to image names in Assets. I need that to display images
array where I want to keep found relations and use it to display all found relationStats in UI
var foundRelations = [SpiritRelation]()
My problems is:
lets say user has selected 2 spirits for example: selectedSpiritsForRelation["golem", "genie"]
I’m able to find and save correctly found relation by
let result3 = spiritRelations.filter{$0.relationSpiritIcons == (selectedSpiritsForRelation) } // = 3rd relation in spiritRelations[]
foundRelations.append(contentsOf: result3)
but after user select another one spirit and array become: selectedSpiritsForRelation["golem", "genie", "maiden"]
same code as for result3 does not work anymore, because how I understand it tries to filter exactly combination of 3, but my expectation is that 2nd relation from spiritRelation[] will be found also
and here is my problem, I cant figure out how to correctly go through spiritRelations[] and find all relations related to selectedSpiritsForRelation[] every time user selects new spirit
You need to use allSatisfy in your filter by checking that all relationSpiritIcons elements exists in selectedSpiritsForRelation
foundRelations = spiritRelations.filter {
$0.relationSpiritIcons.allSatisfy { icon in
selectedSpiritsForRelation.contains(icon)
}
}

dataweave filter and maxBy on nested array list

I have a list of students and their marks for respective subjects. I want to filter all students of a specific grades and then find the student who got maximum marks in a specific object.
[
{
"name": "User 01",
"grade": 1,
"schoolName": "school01",
"marks": {
"english": 10,
"math": 30,
"social": 30
}
},
{
"name": "User 02",
"grade": 1,
"schoolName": "school02",
"marks": {
"english": 10,
"math": 20,
"social": 30
}
}
]
I am able to perform both the operations independently. can someone help me find the student object who got max marks in math in a specific grade.
If I understand your requirement correctly this script does it. Just change the variables grade and topic to the specific values you are interested in.
Generally speaking it is always better to provide example outputs and whatever you got as script to understand better the context, in addition to the input samples.
%dw 2.0
output application/json
var grade = 1
var topic = "math"
---
flatten(
payload map (alumn, order) ->
(alumn.marks pluck ((value, key, index) ->
{
name: alumn.name,
grade: alumn.grade,
result:value,
topic: key
})
)
) // restructure the list to one result per element
filter ((item, index) -> (item.grade == grade)) // filter by grade
maxBy ((item) -> item.result) // get the maximum result
I used it below to achieve it.
%dw 2.0
output application/json
var grade = 1
var topic = "math"
---
payload filter (
((item, index) -> item.grade == grade)
) maxBy ($.marks.math as String {format: "000000"})

Swift filter object array wit another object array

i struggle my had now sine several days with a way to do conditional filter of an object array with another object array.
lack on capabilities to properly abstract here... maybe you ahve some ideas.
I have a given Object Array A but more complex
var ArrA = [{
number: 1,
name: "A"
}, {
number: 2,
name: "C"
}]
And i want to filer for all results matiching id of Object Array B
var ArrB = [{
id: 1,
categorie: "wine"
}, {
id: 3,
categorie: "beer"
}, {
id: 10,
categorie: "juice"
}]
And in the best case moving this directly also together with an if condition.... but i was not able to handle it ... here is where i am now ... which is not working....
let newArray = ArrA.filter{$0.number == ArrB.... }.
if (newArray.count != 0){
// Do something
}
is there a lean way to compare one attribute of every object in an array with one attribute of another every object in an array ?
Lets break this down: You need all arrA objects that matches arrB ids, so first thing first you need to map your arrB to a list of id (because you dont need the other infos)
let arrBid = Set(arrB.map({ $0.id })) // [1, 3, 10]
As commented below, casting it to Set will give you better results for huge arrays but is not mandatory though
Then you just need to filter your first arrA by only keeping object that id is contained into arrBid :
let arrAFilter = arrA.filter({ arrBid.contains($0.number) })
[(number: 1, name: "A")]
and voila

Array .map() returning undefined

This is the structure of the array when I console.log it.
-[]
-0: Array(31)
-0:
-date: "2018-08-26T00:00:00-04:00"
-registered:
-standard: 0
-vip: 0
-waitlisted:
-standard: 0
-vip: 0
This is my code to map the date and the registered (two separate arrays):
this.data.map((value) => value.date);
this.data.map((value) => value.registered['standard']);
I either get an empty array or undefined when I log these. What am I doing wrong?
I want to use these for a chart using ChartJS where:
this.lineChart = new Chart(lineCtx, {
type: 'line',
data: {
datasets: [{
label: (I want the dates to be the labels),
data: (I want the list of standard registrants)
}]...
EDIT:
I've updated the way I get the data to show the following structure:
{
"registrationHistory": [{
"date": "2018-08-26T00:00:00-4:00",
"registered": {
"vip":0,
"standard":0
},
"waitlisted":{
"vip":0,
"standard":0
}
{
,...
}
]}
Your array is two-dimensional and map is iterating only the first dimension, i.e:
-[]
-0: Array(31) // first dimension
-0: // second dimension
-date: "2018-08-26T00:00:00-04:00"
...
This would look like the following JSON string:
[[{"date":"2018-08-26T00:00:00-04:00", ...}]]
Since you haven't provided a full example it's impossible to recommend the most applicable solution:
If you control the data source, remove the first dimension since it appears redundant.
Assuming you only want the first element of the first dimension, refer to that key:
this.data[0].map((value) => value.date);
If your data model is more complex than revealed in your question you'll need to figure out another approach.

Ruby way of summing an array of objects by field

I have an array of objects that I'd like to group by field1 and sum by field2. An example would be a class product that has a title field and a price field.
In an array of products, I have multiple gloves with different prices, and multiple hats with different prices. I'd like to have an array with distinct titles, that aggregate all the prices under the same title.
There's an obvious solution with iterating over the array and using a hash, but I was wondering if there was a "ruby way" of doing something like this? I've seen a lot of examples where Ruby has some unique functionality that applies well to certain scenarios and being a Ruby newbie I'm curious about this.
Thanks
There's a method transform_values added in ruby 2.4 or if you require 'active_support/all', with this you can do something like so:
products = [
{type: "hat", price: 1, name: "fedora"},
{type: "hat", price: 2, name: "sombrero"},
{type: "glove", price: 3, name: "mitten"},
{type: "glove", price: 4, name: "wool"}
]
result = products
.group_by { |product| product[:type] }
.transform_values { |vals| vals.sum { |val| val[:price] } }
# => {"hat"=>3, "glove"=>7}
It's a little unclear to me from the question as asked what your data looks like, so I ended up with this:
Product = Struct.new(:title, :price)
products = [
Product.new("big hat", 1),
Product.new("big hat", 2),
Product.new("small hat", 3),
Product.new("small hat", 4),
Product.new("mens glove", 8),
Product.new("mens glove", 9),
Product.new("kids glove", 1),
Product.new("kids glove", 2)
]
Given that data, this is how I'd go about building a data structure which contains the sum of all the prices for a given title:
sum_by_title = products.inject({}) do |sums, product|
if sums[product.title]
sums[product.title] += product.price
else
sums[product.title] = product.price
end
sums
end
This produces:
{"big hat"=>3, "small hat"=>7, "mens glove"=>17, "kids glove"=>3}
To explain:
Ruby inject takes an initial value and passes that to the iteration block as a "memo". Here, {} is the initial value. The return value from the block is passed into the next iteration as the memo.
The product.title is used as a hash key and the running sum is stored in the hash value. An if statement is necessary because the first time a product title is encountered, the stored value for that title is nil and cannot be incremented.
I probably wouldn't ship this code due to the hidden magic of the hash default value constructor but it's possible to write the same code without the if statement:
sum_by_title = products.inject(Hash.new { 0 }) do |sums, product|
sums[product.title] += product.price
sums
end
Hope you enjoy Ruby as much as I do!

Resources