How to get data from arrays inside of array - reactjs

I'm working on an project that uses React with hooks and typescript. I'm currently trying to get data from arrays inside an array that I get from my json response. Data what i log after data handling looks like this:
[
[
"2021-09-07",
43
],
[
"2021-09-08",
47
],
[
"2021-09-09",
52
]
]
So the question is, how can i get the numerical values seen in the json, to an array?
EDIT: Got it working now. Had to add this:
const numbers = data.map((item: any) => item[1]);
console.log(numbers);
Thanks alot #Ryan Le

You would map all the numbers from the original array like so:
type Data = [string, number][];
const data: Data = [
["2021-09-07", 43],
["2021-09-08", 47],
["2021-09-09", 52]
];
const result = data.map(item => item[1]);
console.log(result);

If by numerical values you mean the second element of each array such as (43 , 47 , 52) you can simply map to a new array like this
const oldArray = [
[
"2021-09-07T08:53:34.4067874+00:00",
43
],
[
"2021-09-07T09:53:34.4067881+00:00",
47
],
[
"2021-09-07T10:53:34.4067884+00:00",
52
]
]
const newArray = oldArray.map((el)=>
el[1])
console.log(newArray)

Related

How can i get all values of a particular key from object array without loop in angular

[{"time":"2016-07-26 09:02:27","type":"aa"},
{"time":"2016-04-21 20:35:07","type":"ae"},
{"time":"2016-08-20 03:31:57","type":"ar"},
{"time":"2017-01-19 22:58:06","type":"ae"},
{"time":"2016-08-28 10:19:27","type":"ae"},
{"time":"2016-12-06 10:36:22","type":"ar"},
{"time":"2016-07-09 12:14:03","type":"ar"},
{"time":"2016-10-25 05:05:37","type":"ae"},
{"time":"2016-06-05 07:57:18","type":"ae"},
{"time":"2016-10-08 22:03:03","type":"aa"},
{"time":"2016-08-13 21:27:37","type":"ae"},
{"time":"2016-04-09 07:36:16","type":"ar"},
{"time":"2016-12-30 17:20:08","type":"aa"},
{"time":"2016-03-11 17:31:46","type":"aa"},
{"time":"2016-05-04 14:08:25","type":"ar"},
{"time":"2016-11-29 05:21:02","type":"ar"},
{"time":"2016-03-08 05:46:01","type":"ar"},
]
here I want only type key all values
like that
Please help me to do so thanks in advance to all.
Simplest way would be to use Array.map method like so:
let array = [{"time":"2016-07-26 09:02:27","type":"aa"},
{"time":"2016-04-21 20:35:07","type":"ae"},
{"time":"2016-08-20 03:31:57","type":"ar"},
{"time":"2017-01-19 22:58:06","type":"ae"},
{"time":"2016-08-28 10:19:27","type":"ae"},
{"time":"2016-12-06 10:36:22","type":"ar"},
{"time":"2016-07-09 12:14:03","type":"ar"},
{"time":"2016-10-25 05:05:37","type":"ae"},
{"time":"2016-06-05 07:57:18","type":"ae"},
{"time":"2016-10-08 22:03:03","type":"aa"},
{"time":"2016-08-13 21:27:37","type":"ae"},
{"time":"2016-04-09 07:36:16","type":"ar"},
{"time":"2016-12-30 17:20:08","type":"aa"},
{"time":"2016-03-11 17:31:46","type":"aa"},
{"time":"2016-05-04 14:08:25","type":"ar"},
{"time":"2016-11-29 05:21:02","type":"ar"},
{"time":"2016-03-08 05:46:01","type":"ar"},
]
array = array.map(i => i.type);
// ["ae", "ar", ...]
array = array.map(i => {return { type: i.type }})
// [ {"type": "ae"}, {"type": "ar"}, ... ]

How do I cast a multidimensional json array to a multidimensional dart list?

I got a JSON file with a long list of data like this.
[
[
[6.25575, 51.83439],
[6.26408, 51.83342]
],
[
[6.25575, 51.83439],
[6.26408, 51.83342]
]
]
When I write:
final List<List<List<double>>> data = await getJson('assets/data.json') as List<List<List<double>>>;
It gives the error: _CastError (type 'List<dynamic>' is not a subtype of type 'List<List<List<double>>>' in type cast).
getJson function:
Future<dynamic> getJson(String file) async {
final String jsonData = await rootBundle.loadString(file);
final dynamic data = await jsonDecode(jsonData);
return data;
}
How can a cast this list of lists to a List<List<List<double>>>?
You need to cast the different Lists individually like below:
final List<List<List<double>>> data = (await getJson('assets/data.json') as List).map((e)=> (e as List).map((e) => (e as List).map((e) => e as double).toList()).toList()).toList();
I don't know if this solution is more readable than the one Victor Eronmosele did come up with but since I ended up making it I will just post it. But the principle is the same. Just another syntax for creating this new list object.
import 'dart:convert';
void main() {
const input = '''
[
[
[6.25575, 51.83439],
[6.26408, 51.83342]
],
[
[6.25575, 51.83439],
[6.26408, 51.83342]
]
]
''';
final typedList = fromJson(jsonDecode(input) as List<dynamic>);
print(typedList); // [[[6.25575, 51.83439], [6.26408, 51.83342]], [[6.25575, 51.83439], [6.26408, 51.83342]]]
print(typedList.runtimeType); // List<List<List<double>>>
}
List<List<List<double>>> fromJson(List<dynamic> list1) => [
for (final list2 in list1)
[
for (final list3 in list2)
[for (final number in list3) number as double]
]
];

How to Access Last Index of Nested Array

I'm trying to figure out how to access the last index of a nested array. The array I am working with is provided by an API call and is VERY LARGE so I'll shorten it below for convenience.
The array:
{
"result": {
"86400": [
[
1381190400,
123.610000,
123.610000,
123.610000,
123.610000,
0.100000,
0.0
],
[
1381276800,
123.610000,
124.190000,
123.900000,
124.180000,
3.991600,
0.0
],
...
[
1600646400,
11078,
11078,
10906.9,
10950.4,
623.00835437,
6841501.73480653
]
]
},
"allowance": {
"cost": 0.015,
"remaining": 9.985,
"upgrade": "For unlimited API access, create an account at ________"
}
}
I would like to access the last index of ['result']['86400'] , which contains:
[
1600646400,
11078,
11078,
10906.9,
10950.4,
623.00835437,
6841501.73480653
]
I am using Flutter in my code, so here is what I have tried:
http.Response historicalResponse = await http.get(historicalRequestURL);
var decodedHistorical = jsonDecode(historicalResponse.body);
var historicalPrice = decodedHistorical['result']['86400'.length - 1][0];
print(historicalPrice);
This causes a few errors stating:
"NoSuchMethodError: The method '[]' was called on null."
"Receiver: null"
"Tried calling: [](0)"
I believe ['86400'.length - 1] is causing the error.
I have also tried using
var historicalPrice = decodedHistorical['result']['86400'][decodedHistorical.length - 1][0];
instead. This doesn't cause an error but it gives me the length of the outer array, which is 2 but I need the length of the inner array named '86400'.
You should implement below way
void parseJson() async {
http.Response historicalResponse = await http.get(historicalRequestURL);
Map decodedHistorical = jsonDecode(historicalResponse.body);
List selectedMap = decodedHistorical['result']['86400'];
var finalValue = selectedMap.last;
print(finalValue);
}
Instead of using var, use List so that you can access its last element by historicalPrice.last getter.
List historicalPrice = decodedHistorical['result']['86400'];
List lastElement=historicalPrice.last;

How to return the index from two array?

I have two array my desired result is to return the index from matching values. How to do that?
For instance I have these two array:
const arr1 = [ monkey, lion, giraffe, bear, ant, fish, dinosaur ]
cosnt arr2 = [ lion, giraffe, bear ]
How to return the result as the index from matching values?
You can try like this.
const arr1 = [ 'monkey', 'lion', 'giraffe', 'bear', 'ant', 'fish', 'dinosaur' ]
const arr2 = [ 'lion', 'giraffe', 'bear' ];
let index = [];
arr2.forEach(function(a,i){
index.push(arr1.indexOf(a));
});
console.log(index);
//another way using map function
let result = arr2.map((a,i)=>{
return arr1.indexOf(a);
})
console.log(result);

Json object pushed into javascript array

I have this javascript array:
var data = ([
['Price', 'Time'],
['1.10661', 1467923348, ],
['1.10675', 1467923349, ],
['1.10681', 1467923350, ],
['1.10690', 1467923351, ],
]);
Im sending a request to my server using ajax and Im reciving as response this json objects:
[{"PRICE":"1.10662","TIME":"1467923352"},{"PRICE":"1.10663","TIME":"1467923353"}]
What im trying to do is to parse the response and push the objects inside of my array so the final result should be this:
var data = ([
['Price', 'Time'],
['1.10661', 1467923348, ],
['1.10675', 1467923349, ],
['1.10681', 1467923350, ],
['1.10690', 1467923351, ],
['1.10662', 1467923352, ],
['1.10663', 1467923353, ],
]);
Please keep in mind the number of objets I receive as response changes in every request. In the example Im giving is received just two objects but this changes all the time.
Thank you in advance
I guess you can break your problem down into 2 parts. First think about how you can make the response data to look the same as data, in terms of data format. Then merge the 2 arrays into one.
Here is my approach. First use the map api to go through every object in resp and extract the property value of PRICE and TIME and store it into a new array. This should leave you with an array of array with position 0 as price and position 1 as time.
[ [ '1.10662', '1467923352' ], [ '1.10663', '1467923353' ] ]
Then use the concat api to combine the 2 arrays into one.
Example:
var data = ([
['Price', 'Time'],
['1.10661', 1467923348, ],
['1.10675', 1467923349, ],
['1.10681', 1467923350, ],
['1.10690', 1467923351, ],
]);
var resp = [{"PRICE":"1.10662","TIME":"1467923352"},{"PRICE":"1.10663","TIME":"1467923353"}];
data = data.concat(
resp.map(entity => { return [ entity.PRICE, entity.TIME ]; })
);
Output:
[ [ 'Price', 'Time' ],
[ '1.10661', 1467923348 ],
[ '1.10675', 1467923349 ],
[ '1.10681', 1467923350 ],
[ '1.10690', 1467923351 ],
[ '1.10662', '1467923352' ],
[ '1.10663', '1467923353' ] ]
You might want to read more about the map and concat api here;
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/concat
Thank you very much for the answers! I found the solution, let me share it with you.
(The example is a bit different but the idea is exactly the same)
<html>
<body>
<script>
var myArray = [{"ASK":"1.10662","TIME":"1467923348"},{"ASK":"1.10663","TIME":"1467923346"},{"ASK":"1.10661","TIME":"1467923340"},{"ASK":"1.10663","TIME":"1467923346"},
{"ASK":"1.10661","TIME":"1467923340"}];
var data = ([
['PRICE', 'TIME'],
]);
var actualrows = data.length
var finalrows = data.length + myArray.length;
for( var i=actualrows; i<finalrows; i++ ) {
data.push( [] );
}
while(actualrows < finalrows){
var column = 0;
while(column <2){
data[actualrows][0] = myArray[actualrows-1]['ASK'];
data[actualrows][1] = myArray[actualrows-1]['TIME'];;
column++;
}
actualrows++ ;
}
</script>
</body>
</html>

Resources