I want to enter the first value from every array inside a 2d array, I get the 2d array from the server and my intentions are to use it in one of the client pages (as chart data).
Here is the relevant code:
React.useEffect(() => {
fetch("http://localhost:3001/bitcoin")
.then((res) => res.json())
.then((data) => setData(data.message))
.then((dates) => {
//code right here
})
}, []);
Any idea how to implement it?
first method :
you can use for...of like this :
const Arr = [
[ 1,2,3,4],
['one', 'two' , 'three'],
['un' ,'deux', 'trois' ],
]
const ArrOfFirstValues = []
for(key of Arr){
ArrOfFirstValues.push(key[0])
}
console.log(ArrOfFirstValues)
the output is : [ 1, 'one', 'un' ]
Second method :
you can use .map to iterate it :
const Arr = [
[ 1,2,3,4],
['one', 'two' , 'three'],
['un' ,'deux', 'trois' ],
]
console.log(Arr )
const ArrOfFirstValues = Arr.map(arr => arr[0])
console.log(ArrOfFirstValues)
the output will be :
[ 1, 'one', 'un' ]
It's too easy :
const twoDArray = [
["a", "b", "c"],
["A", "B", "C"],
["aa", "bb", "cc"],
["AA", "BB", "CC"] ]
const firstElements = twoDArray.map(item => item[0]);
console.log(firstElements);
// answer: [ 'a', 'A', 'aa', 'AA' ]
Let me know if it is what you exactly need.
Update :
That was the main idea you need and you can implement like this:
React.useEffect(() => {
fetch("http://localhost:3001/bitcoin")
.then(res => res.json())
.then(jsonData => {
// I assume that jsonData is your 2D array
const twoDimensionArr = jsonData ;
setData(twoDimensionArr);
const firstElementsArr = twoDimensionArr.map(item => item[0]);
console.log(firstElementsArr);
})
}, []);
Related
I am looping the database to get a list of countries with continents.
array: [
0 => array: [
"country" => "BE"
"continent" => "EU"
1 => array: [
"country" => "BG"
"continent" => "EU"
]
...
]
From that result, I want to create an array that shows all the continents with the countries inside.
array:[
0 => array: [
"continent" => "EU"
"countries" => [
"country" => "BE"
"country" => "BG"
]
]
Suppose this is your array
$arr = [
[
"country" => "BE",
"continent" => "EU",
],
[
"country" => "BG",
"continent" => "EU",
]
];
Then this returns what you expected.
collect($arr)->groupBy('continent')->mapWithKeys(function ($group, $continent) {
return [
'continent' => $continent,
'countries' => $group->pluck('country')->toArray()
];
});
If you need just to group countries by continent, simple way to achieve this by mapToGroups() method for collections
$input = [
['country' => 'BE', 'continent' => 'EU'],
['country' => 'BG', 'continent' => 'EU'],
['country' => 'BU', 'continent' => 'AF'],
['country' => 'BY', 'continent' => 'EU'],
];
$grouped = collect($input)
->mapToGroups(fn ($country) => [$country['continent'] => $country['country']])
->toArray(); // if you need array at the end
This will be resulted in
You will need to some how group your results by the continent. One way to do that is to loop over the initial collection and build a new array keyed by the continent.
However, seeing that you are using Laravel just group the collection by the continent.
$countries = [
['country' => 'A', 'continent' => 'aa'],
['country' => 'B', 'continent' => 'bb'],
['country' => 'C', 'continent' => 'aa'],
['country' => 'D', 'continent' => 'aa'],
['country' => 'E', 'continent' => 'aa'],
['country' => 'F', 'continent' => 'bb'],
];
// Because my data is an array I just turn that into a collection.
// But an Eloquent query builder ->get would already return a collection.
$continents = collect($countries)->groupBy('continent');
foreach ($continents as $continent => $items) {
echo "Countries for " . $continent . "\n";
foreach ($items as $country) {
echo $country['country'] . "\n";
}
}
/**
Output:
Countries for aa
A
C
D
E
Countries for bb
B
F
**/
Here the array of hashes:
array = [
{:ID => "aaa", :phase => "alpha", :quantity => 80},
{:ID => "aaa", :phase => "beta", :quantity => 160}
]
I'm trying to transform the value of :phase into a key and to assign its value taking the value of :quantity, as follow:
array = [
{:ID => "aaa", :"alpha" => 80},
{:ID => "aaa", :"beta" => 160}
]
Thanks!
I would do it like this:
array = [
{:ID => "aaa", :phase => "alpha", :quantity => 80},
{:ID => "aaa", :phase => "beta", :quantity => 160}
]
array.map { |hash| { :ID => hash[:ID], hash[:phase].to_sym => hash[:quantity] } }
#=> [{:ID=>"aaa", :alpha=>80}, {:ID=>"aaa", :beta=>160}]
You can do it like this:
array.map do |hash|
new_key = hash.delete(:phase)
quantity = hash.delete(:quantity)
hash[new_key] = quantity
hash
end
I have an array A that looks like this:
A = [ { "id" => "1234", "name" => "audi", "isCool" => false },
{ "id" => "5678", "name" => "acura", "isCool" => false },
{ "id" => "9101112", "name" => "bentley", "isCool" => true },
{ "id" => "13141516", "name" => "rollsroyce", "isCool" => true },
{ "id" => "17181920", "name" => "toyota", "isCool" => true } ]
and I have an array B that looks like this:
B = ["1234", "13141516”]
I am trying to select only elements from array A that match array A's ids with Array Bs elements.
So the returned results I would like is:
C = [ { "id" => "1234", "name" => "audi", "isCool" => false },
{ "id" => "13141516", "name" => "rollsroyce", "isCool" => true } ]
Is there an easy way to go about this?
I have currently tried this but obviously not a good idea:
a.select {|x| x['id'] == B.first || B.last}
But obviously this is not dynamic, because what if I had 3 or 4 elements in array B.
A.select { |x| B.include?(x['id']) }
I have two arrays say: x=[1,2,3] and y=['a', 'b', 'c']. I want to create a json using x and y arrays in rails console. What is the optimized way to do it.
The desired JSON should looks like this:
{
"obj":
[
{
"key":"a",
"value": 1
},
{
"key":"b",
"value": 2
},
{
"key":"c",
"value": 3
}
]
}
x = [1,2,3] and y = ['a', 'b', 'c']
{obj: y.zip(x).map { |k, v| {key: k, value: v} } }
#⇒ {
# :obj => [
# {
# :key => "a",
# :value => 1
# },
# {
# :key => "b",
# :value => 2
# },
# {
# :key => "c",
# :value => 3
# }
# ]
# }
If you insist on having string keys:
{ 'obj' => y.zip(x).map { |k, v| { 'key' => k, 'value' => v } } }
To get a json out of the hash, just call to_json on it.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
In Perl, from the below hash:
{
'item3' => {
'floors' => [ 'a', 'b', 'c' ]
},
'item1' => [ 'special' ]
'item2' => {
'books' => {
'topics' => [ 'epics' ]
},
'sports' => [ 'tennis' ]
},
'item5' => {
'groups' => {
'teams' => [ 'x', 'y' ]
}
},
'offers' => {
'list' => [ 'bags' ]
}
}
Need to parse only last values in each sub level of hash where it is always be an array.
Only final child entries(array values) need to be listed.
Expecting the output in one single array:
[ 'a', 'b', 'c', 'special', 'epics', 'tennis', 'x', 'y', 'bags' ]
no idea how to proceed....please help me to get rid of this.
Advance Thanks!!!!
Recursion assumes that data structure consists of hashes and arrays only, and array elements are not references,
use strict;
use warnings;
use Data::Dumper;
my %h;
#h{ 1..5 } = (
{ 'item3' => { 'floors' => [ 'a', 'b', 'c' ] } },
{ 'item1' => [ 'special' ] },
{ 'item2' => {
'books' => { 'topics' => [ 'epics' ] },
'sports' => [ 'tennis' ]
}},
{ 'item5' => { 'groups' => { 'teams' => [ 'x', 'y' ] } } },
{ 'offers' => { 'list' => [ 'bags' ] } },
);
print Dumper [ arrvals(\%h) ];
sub arrvals {
my ($ref) = #_;
return ref($ref) eq "ARRAY"
? #$ref
: map arrvals($_), values %$ref;
}