Amount of all goals of one team (from JSON)
If you insist on keeping code as it is, you could probably add another object to track goals like this:
function countGames() {
var data = this.$store.getters.games;
var arr1 = [];
var goalsPerTeam = []; // keep track of goals here
var obj1 = {};
//Here I got all unique Team IDs
function getMatches() {
for (var i in data) {
obj1[data[i].team_1_id] = (obj1[data[i].team_1_id] || 0) + 1;
obj1[data[i].team_2_id] = (obj1[data[i].team_2_id] || 0) + 1;
// add goals count
if (goalsPerTeam[data[i].team_1_id] === undefined) {
goalsPerTeam[data[i].team_1_id] = parseInt(data[i].team_1_goals_quantity);
} else {
goalsPerTeam[data[i].team_1_id] += parseInt(data[i].team_1_goals_quantity);
}
if (goalsPerTeam[data[i].team_2_id] === undefined) {
goalsPerTeam[data[i].team_2_id] = parseInt(data[i].team_2_goals_quantity);
} else {
goalsPerTeam[data[i].team_2_id] += parseInt(data[i].team_2_goals_quantity);
}
};
Object.keys(obj1).forEach(function(el, data) {
arr1.push( [ el, obj1[el], goalsPerTeam[el]] ); // update this
});
};
getMatches();
var result = arr1.map(
// add here finally
([team_id, matches, goals]) => ({team_id, matches, goals}) //here I got { {team_id: "119", matches: 3}, {team_id: "120", matches: 1} ... }
);
return result;
}
Getting largest value from JSON and displaying related data (API/Javascript)
This will loop over the array only once and retrieve all stats in one go:
const input = { "elements": [{ "first_name": "Petr", "second_name": "Cech", "minutes": 585, "goals_scored": 0, "assists": 0, "clean_sheets": 1, }, { "first_name": "Bernd", "second_name": "Leno", "minutes": 135, "goals_scored": 0, "assists": 0, "clean_sheets": 0, }, { "first_name": "Mesut", "second_name": "Özil", "minutes": 510, "goals_scored": 2, "assists": 0, "clean_sheets": 2, } ]};
const stats = input.elements.reduce((stats, player) => { ['minutes', 'goals_scored', 'assists', 'clean_sheets'].forEach(key => { if (player[key] > stats[key].max) { stats[key].max = player[key]; stats[key].bestPlayer = player; } }); return stats;}, { minutes: {max: 0, bestPlayer: null}, goals_scored: {max: 0, bestPlayer: null}, assists: {max: 0, bestPlayer: null}, clean_sheets: {max: 0, bestPlayer: null}});
console.log('minutes', stats.minutes);console.log('goals_scored', stats.goals_scored);console.log('assists', stats.assists);console.log('clean_sheets', stats.clean_sheets);
Sort a List of json objects in FLutter
Solution
Implement a model class for json. Implement Comparable interface and then sort it.
Now that you have already have modal class. I have taken a dummy class to explain how to implement this
class Student implements Comparable {
int marks;
String name ;
Student(this.marks,this.name);
@override
int compareTo(other) {
if (this.marks < other.marks) {
return 1;
}
else if (this.marks > other.marks) {
return -1;
}
else{
return 0;
}
}
}
void main(){
List<Student> myList = [];
myList.add(Student(20,"A1"));
myList.add(Student(-1,"A2"));
myList.add(Student(-340,"A3"));
myList.add(Student(-30,"A4"));
myList.add(Student(2340,"A5"));
print('Before sort');
for(var item in myList){
print(item.marks.toString()+" "+item.name);
}
myList.sort();
print('After sort');
for(var item in myList){
print(item.marks.toString()+" "+item.name);
}
Comparator<Student> nameSorter = (a, b) => a.name.compareTo(b.name);
myList.sort(nameSorter);
print('After sort by name');
for(var item in myList){
print(item.marks.toString()+" "+item.name);
}
}
You can run this code
https://dartpad.dev/?null_safety=true here
Get data from json and use just one result as value
You have an Object which has, amongst others, an array of objects named standing
and they in turn have teamName
property. So to get the first one you'll do
if($details->standing[0]->teamName == 'Manchester United')
Or you can loop over standing
and get all of them if in case there are multiple entries
Like
foreach($details->standing as $record)
{
if($record->teamName == 'Manchester United')
$gamesPlayed=$record->playedGames;
}
Node js loop through JSON and get latest values per team based on the timestamp
If you can use lodash
, this can be very simple and readable
const _ = require('lodash');
const input =
[
{
timestamp: '1571967208',
team: 'team1',
goals: '2'
},
{
timestamp: '1571967150',
team: 'team2',
goals: '1'
},
{
timestamp: '1571967110',
team: 'team1',
goals: '0'
},
{
timestamp: '1571967067',
team: 'team3',
goals: '4'
},
{
timestamp: '1571966896',
team: 'team1',
goals: '5'
}
];
const grouped = _.groupBy(input, "team");
const latestGoal = Object.keys(grouped).map(item => _.sortBy(grouped[item], ["timestamp"])[0]));
Get data from json and use just one result as value
You have an Object which has, amongst others, an array of objects named standing
and they in turn have teamName
property. So to get the first one you'll do
if($details->standing[0]->teamName == 'Manchester United')
Or you can loop over standing
and get all of them if in case there are multiple entries
Like
foreach($details->standing as $record)
{
if($record->teamName == 'Manchester United')
$gamesPlayed=$record->playedGames;
}
make the average with 2 values from Json with AngularJS
Your code has a few issues that I will try to make it clear for you. Let's start with the HTML.
ng-if="stat.mediaGoals()"
will ever be matched, because the object stat
does not have a mediaGoals
function, and even if it has it, your mediaGoals
function returns nothing, undefined
to be more specific. Also, mediaGoals
in this case, is a real performance killer.
My recommendation is to parse/convert the JSON
in the service that loads it, converting the content into something more easy to handle in the HTML.
As I don't know the code that loads the JSON
, I will adapt an illustrative example of your code and hope it helps.
Suppose we are using $http
to load the JSON
from an API
$http(requestConfig)
.then(function(response){
var players = [];
for (var i = 0; i < response.data.length; i++) {
var item = response.data[i];
var player = {
player: item.player,
stats: { media: 0 }
};
var tmp_goals = 0;
var tmp_mins = 0;
for (var x=0; x < item.stats.length; x++) {
var stat = item.stats[x];
player.stats[stat.name] = stat.value;
switch(stat.name) {
case 'goals':
tmp_goals = stat.value;
break;
case 'mins_played':
tmp_mins = stat.value;
break;
}
}
if (tmp_mins > 0) {
player.stats.media = tmp_goals/tmp_mins;
}
players.push(player);
}
return players;
});
Now, every time we get a single item from this list, it will look like this:
{
player: {
info: ...same from anwser
},
stats: {
appearances: 80,
backward_pass: 308,
draws: 23,
fwd_pass: 1533,
goal_assist: 2,
goals: 5,
losses: 20,
media: 0.0007191140514885661,
mins_played: 6953,
wins: 48
}
}
Note that I did not include some info for brevity. But now, when we set the value to $scope.Jugador
with one item from the parsed/converted list, the HTML will become much simpler, not need of ngRepeat
or ngIf
.
<div class="stadistics">
<div class="cont-desc-player">
<div class="desc-player separador">
<span class="txt-estadistics">Appearances</span>
<span class="num-estadistics">{{Jugador.stats.appearances}}</span>
</div>
<div class="desc-player separador">
<span class="txt-estadistics">Goals</span>
<span class="num-estadistics">{{Jugador.stats.goals}}</span>
</div>
<div class="desc-player separador">
<span class="txt-estadistics">Assists</span>
<span class="num-estadistics">{{Jugador.stats.goal_assist}}</span>
</div>
<div class="desc-player separador">
<span class="txt-estadistics">Goals per match</span>
<span class="num-estadistics">{{Jugador.stats.media}}</span>
</div>
</div>
</div>
Or probably you want to keep the ngIf
and only show the info if the value is greater than 0
<div class="desc-player separador" data-ng-if="Jugador.stats.media > 0">
<span class="txt-estadistics">Goals per match</span>
<span class="num-estadistics">{{Jugador.stats.media}}</span>
</div>
It is all up to you from now on, hope it help.
EDIT:
If you want to continue with your approach on mediaGoals
function, then you need to invoke it in your controller before you set the value to Jugador
, so, it needs some changes.
$scope.Jugador = mediaGoals($scope.players[0]);
function mediaGoals(jugador) {
var tmp_goals = 0;
var tmp_mins = 0;
for (var i = 0; i < jugador.stats.length; i++) {
switch(jugador.stats[i].name) {
case 'goals':
tmp_goals = jugador.stats[i].value;
break;
case 'mins_played':
tmp_mins = jugador.stats[i].value;
break;
}
}
jugador.stats.push({ name: 'media', value: tmp_mins > 0 ? tmp_goals/tmp_mins : 0 });
return jugador;
}
Adjust $scope.players[0]
to your needs.
Now, your HTML can change to this
<div class="desc-player separador" ng-if="stat.name == 'media'">
<span class="txt-estadistics">Goals per match</span>
<span class="num-estadistics">{{stat.value}}</span>
</div>
Parse and modify an array in Javascript
Thought these two operation can be done together for clean writing you can do the following.
map
to add the difference between the two property in a new property called d
using Math.abs
to keep the difference positive.
let teams = [{"team":"Arsenal","f":"79","a":"36"},
{"team":"Liverpool","f":"67","a":"30"},
{"team":"Manchester_U","f":"87","a":"45"},
{"team":"Newcastle","f":"74","a":"52"},
{"team":"Leeds","f":"53","a":"37"},
{"team":"Chelsea","f":"66","a":"38"},
{"team":"West_Ham","f":"48","a":"57"},
{"team":"Aston_Villa","f":"46","a":"47"},
{"team":"Tottenham","f":"49","a":"53"},
{"team":"Blackburn","f":"55","a":"51"},
{"team":"Southampton","f":"46","a":"54"},
{"team":"Middlesbrough","f":"35","a":"47"},
{"team":"Fulham","f":"36","a":"44"},
{"team":"Charlton","f":"38","a":"49"},
{"team":"Everton","f":"45","a":"57"},
{"team":"Bolton","f":"44","a":"62"},
{"team":"Sunderland","f":"29","a":"51"},
{"team":"Ipswich","f":"41","a":"64"},
{"team":"Derby","f":"33","a":"63"},
{"team":"Leicester","f":"30","a":"64"}];
teams.map((t) => t['d'] = Math.abs(t.f - t.a))
console.log(teams);
Related Topics
Javascript Function Not Defined Error (But It Is Defined)
Dynamically Add Variable Name Value Pairs to Json Object
Print Pdf Directly from JavaScript
How to Partition Input Field to Appear as Separate Input Fields on Screen
Using Thymeleaf Variable in Onclick Attribute
Google Script to See If Text Contains a Value
Accessing Ejs Variable in JavaScript Logic
Blocking Device Rotation on Mobile Web Pages
How Display Selected Item from Bootstrap 4 Drop-Down Item Menu
Javascript or Jquery Browser Back Button Click Detector
Regex to Replace Everything Except Numbers and a Decimal Point
How to Display a Success Message After Redirecting the User Back to My Home Page
How to Change Value of Object Which Is Inside an Array Using JavaScript or Jquery
How to Convert Gmt Time to Ist Time in JavaScript
Horizontal Scrollbar on Top and Bottom of Table
How to Hide the Parent Div If All Its Child Div Are Hidden