Related
"periodos": [
{
"id": 3,
"transporte_id": 2,
"ativo": 1,
"periodo": "MANH\u00c3",
"corte": "12:00",
"data": null,
"week": [0, 1, 1, 1, 1, 1, 1]
},
{
"id": 4,
"transporte_id": 2,
"ativo": 1,
"periodo": "TARDE",
"corte": "18:00",
"data": null,
"week": [0, 1, 1, 1, 1, 1, 1]
},
{
"id": 7,
"transporte_id": 2,
"ativo": 1,
"periodo": "PERIODO PARA O DIA 16",
"corte": "10:00",
"data": "2022-12-16",
"week": [0, 1, 1, 1, 1, 1, 1]
}
]
I have this array, if the date object is different from null, I would like it to make a filter confirming whether the selected date is equal to today's date, if so, it returns the object that is equal to today's date
if the date is null or is not equal to today, it returns this filter
return this.periodos.filter( transpId => transpId.ativo === (1) && transpId.transporte_id === (this.metodoId) && transpId.week[d.getDay()] === 1 ) ;
I would like to put the code inside my function that already exists
filterPeriodos() {
const object = this.formGeral.value.data;
const jsDate = new Date(object.singleDate?.jsDate);
jsDate.setUTCHours(23, 59, 59, 999);
this.dataFormat = jsDate;
const d = new Date(jsDate );
if (this.storeS.layout.emp.id === 1) {
if (this.formGeral.value.entregaBool){
return this.periodos.filter( transpId => transpId.ativo === (1) && transpId.transporte_id === (this.metodoId) && transpId.week[d.getDay()] === 1 ) ;
}
}
return this.periodos;
}
I tried putting an if conditional inside my this.periodos.filter, but I didn't succeed
You can do it like so:
const arr=[{id:3,transporte_id:2,ativo:1,periodo:"MANHÃ",corte:"12:00",data:null,week:[0,1,1,1,1,1,1]},{id:4,transporte_id:2,ativo:1,periodo:"TARDE",corte:"18:00",data:null,week:[0,1,1,1,1,1,1]},{id:7,transporte_id:2,ativo:1,periodo:"PERIODO PARA O DIA 16",corte:"10:00",data:"2022-12-16",week:[0,1,1,1,1,1,1]}];
let currentDate = new Date()
let query = `${currentDate.getFullYear()}-${currentDate.getMonth() + 1}-${currentDate.getDate()}`
const result = arr.filter(e => e.data == query)
console.log(result)
Simply get the current date and construct the query in the right format, then filter with it.
I'm currently working on a Tennis scorer where the user inputs the information for each point and then gets saved in an object. The way I do this is whenever a set ends, a new object is created inside a global object with the information of the match at that moment, so the information for each set is cumulative. An example of a match would look like this:
"sets": {
"set1": {
"equipo1": {
"breakPoints": 5,
"breakPointsExito": 0,
"games": 5,
"jugador1": {
"smashes": 0,
"smashesExito": 5,
"unfError": 0,
"winners": 0,
},
"jugador2": {
"smashes": 0,
"smashesExito": 1,
"unfError": 0,
"winners": 2,
},
"puntosOro": 0,
},
"equipo2": {
"breakPoints": 3,
"breakPointsExito": 1,
"games": 7,
"jugador1": Object {
"smashes": 0,
"smashesExito": 5,
"unfError": 0,
"winners": 2,
},
"jugador2": {
"smashes": 0,
"smashesExito": 2,
"unfError": 0,
"winners": 3,
},
"puntosOro": 2,
},
},
"set2": {
"equipo1": {
"breakPoints": 8,
"breakPointsExito": 1,
"games": 2,
"jugador1": Object {
"smashes": 0,
"smashesExito": 8,
"unfError": 0,
"winners": 2,
},
"jugador2": {
"smashes": 0,
"smashesExito": 3,
"unfError": 0,
"winners": 3,
},
"puntosOro": 1,
},
"equipo2": {
"breakPoints": 4,
"breakPointsExito": 2,
"games": 2,
"jugador1": Object {
"smashes": 0,
"smashesExito": 9,
"unfError": 0,
"winners": 2,
},
"jugador2": {
"smashes": 0,
"smashesExito": 5,
"unfError": 0,
"winners": 8,
},
"puntosOro": 2,
},
},
}
Now, what I want to do is to show this information by sets, so, let's say we wanted to show the information of the 3rd set, we would have to subtract the sum of the previous sets. I was wondering if there was any way to make this efficiently since the keys of each set object are essentially the same, with only the value changing.
Right now I made it work by creating an object based on the sets results, but it's very ugly and I hope there's a way of better doing this:
if (value == 0) {
matchFunc([
{
name: "Break Points",
equipo1: infoEquipo1.breakPointsExito,
equipo2: infoEquipo2.breakPointsExito,
},
{
name: "Puntos de Oro",
equipo1: infoEquipo1.puntosOro,
equipo2: infoEquipo2.puntosOro,
},
{
name: "Winners",
equipo1:
infoMatchEquipo1.jugador1.winners +
infoMatchEquipo1.jugador2.winners,
equipo2:
infoMatchEquipo2.jugador1.winners +
infoMatchEquipo2.jugador2.winners,
},
{
name: "Smashes",
equipo1:
infoMatchEquipo1.jugador1.smashesExito +
infoMatchEquipo1.jugador2.smashesExito,
equipo2:
infoMatchEquipo2.jugador1.smashesExito +
infoMatchEquipo2.jugador2.smashesExito,
},
{
name: "Unforced Errors",
equipo1:
infoMatchEquipo1.jugador1.unfError +
infoMatchEquipo1.jugador2.unfError,
equipo2:
infoMatchEquipo2.jugador1.unfError +
infoMatchEquipo2.jugador2.unfError,
},
]);
}
if (value == 1) {
matchFunc([
{
name: "Winners",
equipo1:
infoSets.set1.equipo1.jugador1.winners +
infoSets.set1.equipo1.jugador2.winners,
equipo2:
infoSets.set1.equipo2.jugador1.winners +
infoSets.set1.equipo2.jugador2.winners,
},
{
name: "Smashes",
equipo1:
infoSets.set1.equipo1.jugador1.smashesExito +
infoSets.set1.equipo1.jugador2.smashesExito,
equipo2:
infoSets.set1.equipo2.jugador1.smashesExito +
infoSets.set1.equipo2.jugador2.smashesExito,
},
{
name: "Unforced Errors",
equipo1:
infoSets.set1.equipo1.jugador1.unfError +
infoSets.set1.equipo1.jugador2.unfError,
equipo2:
infoSets.set1.equipo2.jugador1.unfError +
infoSets.set1.equipo2.jugador2.unfError,
},
]);
}
if (value == 2) {
matchFunc([
{
name: "Winners",
equipo1:
infoSets.set2.equipo1.jugador1.winners +
infoSets.set2.equipo1.jugador2.winners -
(infoSets.set1.equipo1.jugador1.winners +
infoSets.set1.equipo1.jugador2.winners),
equipo2:
infoSets.set2.equipo2.jugador1.winners +
infoSets.set2.equipo2.jugador2.winners -
(infoSets.set1.equipo2.jugador1.winners +
infoSets.set1.equipo2.jugador2.winners),
},
{
name: "Smashes",
equipo1:
infoSets.set2.equipo1.jugador1.smashesExito +
infoSets.set2.equipo1.jugador2.smashesExito -
(infoSets.set1.equipo1.jugador1.smashesExito +
infoSets.set1.equipo1.jugador2.smashesExito),
equipo2:
infoSets.set2.equipo2.jugador1.smashesExito +
infoSets.set2.equipo2.jugador2.smashesExito -
(infoSets.set1.equipo2.jugador1.smashesExito +
infoSets.set1.equipo2.jugador2.smashesExito),
},
{
name: "Unforced Errors",
equipo1:
infoSets.set2.equipo1.jugador1.unfError +
infoSets.set2.equipo1.jugador2.unfError -
(infoSets.set1.equipo1.jugador1.unfError +
infoSets.set1.equipo1.jugador2.unfError),
equipo2:
infoSets.set2.equipo2.jugador1.unfError +
infoSets.set2.equipo2.jugador2.unfError -
(infoSets.set1.equipo2.jugador1.unfError +
infoSets.set1.equipo2.jugador2.unfError),
},
]);
}
I'm sorry, I know that this looks horrendous, but it's the only way i've been able to make it work. The if(value) refers to the sets, and the 0 is for the entire match.
If I have a JavaScript object such as:
const group = {
Gp1: 1,
Gp12:1,
Gp11:2,
Gp10: 0,
Gp2: 1,
Gp5: 4,
Gp3: 4,
Gp4: 4,
Gp6: 4,
};
I want to make sortable ascending by key of the array
with this code
const sortable = Object.fromEntries(
Object.entries(group).sort(([,a],[,b]) => a-b)
);
console.log(sortable);
I end up with
{
Gp1: 1,
Gp10: 0,
Gp11: 2,
Gp12: 1,
Gp2: 1,
Gp3: 4,
Gp4: 4,
Gp5: 4,
Gp6: 4
}
Is there a way to sort the properties based on key array? So that I end up with
{
Gp1: 1,
Gp2: 1,
Gp3: 4,
Gp4: 4,
Gp5: 4,
Gp6: 4,
Gp10: 0,
Gp11: 2,
Gp12: 1,
}
You can use string#localeCompare to sort based on numeric value by passing {numeric: true}.
const o = { Gp1: 1, Gp10: 0, Gp11: 2, Gp12: 1, Gp2: 1, Gp3: 4, Gp4: 4, Gp5: 4, Gp6: 4 },
result = Object.fromEntries(Object.entries(o).sort((a,b) => a[0].localeCompare(b[0], undefined, {numeric: true})));
console.log(result);
Are you finding something like this?
const sortable = Object.fromEntries(
Object.entries(group).sort(([a,],[b,]) => parseInt(a.replace('Gp', '')) - parseInt(b.replace('Gp', '')))
);
Am trying to display all values for each country in a Google Geochart from data sent from my database (via JSON), but only the last row ever displays ('Supplier 2' in the case highlighted below). I have reviewed this answer and attempted to incorporate the suggested group() method; however this produces a console error which I am unable to successfully debug: 'unexpected token }', which refers to the closing curly bracket in the var groupData declaration.
This is what currently shows, without using any group() method. I need 'Supplier 1' to also display.
This is the code:
function incAvailableCountry() {
$.ajax({
url: "inc-analysis/country-available.php,
dataType: "json"
}).done(function(jsonData){
var data = new google.visualization.DataTable(jsonData);
var groupData = google.visualization.data.group(
data,
[0, 1],
[{
aggregation: google.visualization.data.count,
column, 0
}]);
var options = {
width: 'auto',
keepAspectRatio: true,
legend: 'none'
};
for (var i = 0; i < data.getNumberOfRows(); i++) {
var locationRows = groupData.getFilteredRows([{
column: 0,
value: data.getValue(i, 0)
}]);
var nameTooltip = '';
locationRows.forEach(function(index){
if (nameTooltip !== '') {
nameTooltip += ', ';
}
nameTooltip += groupData.getValue(index, 1);
});
data.setValue(i, 1, nameTooltip);
}
var chart = new google.visualization.GeoChart(document.getElementById('incAvailableCountry'));
chart.draw(data, options);
});}
PHP:
<?php include '../core/init.php';
$query = mysqli_query($conn, "(SELECT Country, Supplier
FROM table
GROUP BY Supplier)
ORDER BY Country");
$table = array();
$table['cols'] = array(
array('label' => 'Country', 'type' => 'string'),
array('label' => 'Supplier', 'type' => 'string')
);
$rows = array();
while ($r1 = mysqli_fetch_assoc($query)) {
$temp = array();
$temp[] = array('v' => (string)$r1['Country']);
$temp[] = array('v' => (string)$r1['Supplier']);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);
echo $jsonTable;
Resulting JSON:
{"cols":[
{"label":"Country","type":"string"},
{"label":"Supplier","type":"string"}],"rows":[
{"c":[{"v":"Spain"},
{"v":"Supplier 1"}]},
{"c":[{"v":"Spain"},
{"v":"Supplier 2"}]}]}
HTML:
<script src="https://www.google.com/jsapi"></script>
<script>google.charts.load('current', {'packages': ['geochart'], 'mapsApiKey': 'key...'});</script>
<div id="incAvailableCountry"></div>
in the group method, column should be followed by a colon :, instead of a comma ,
var groupData = google.visualization.data.group(
data,
[0, 1],
[{
aggregation: google.visualization.data.count,
column, 0
}]);
change to...
var groupData = google.visualization.data.group(
data,
[0, 1],
[{
aggregation: google.visualization.data.count,
column: 0,
type: 'number'
}]
);
i have this following Array :
var objRow = [
{
2011-09-20 : [0, 100, 0],
customerID : C1101,
ANI : 1234
},
{
2011-09-25 : [0, 0, 0],
customerID : C1101,
ANI : 1234
},
{
2011-09-20 : [0, 500, 0],
customerID : C1102,
ANI : 5678
},
{
2011-09-22 : [0, 0, 50],
customerID : C1102,
ANI : 5678
}
]
I want to create CSV Data from array above. But, i have problem to change that array to this CSV pattern :
1234, C1101, 0, 0, 100, 0, 0, 0
5678, C1102, 0, 0, 500, 0, 0, 50
I try to group the customerID using reduce, and because the first index in every object is date. I have some array of dates :
var dateArr = ["2011-09-20", "2011-09-22", "2011-09-25"];
And this is my code :
var result = objRow.reduce(function(prev, curr, index, arr) {
var num = curr["customerID"];
if (!prev[num]) {
prev[num] = [];
}
for (var j = 0; j < dateArr.length; j++) {
prev[num].push(curr[dateArr[j]]);
}
return prev;
}, {});
Update Question
For number combination in date index. I use this rules :
[0, 100, 0] // from first Object
[0, 0, 0] // from second Object
fistObject_firstIndex, secondObject_firstIndex, firstObject_secondIndex, secondObject_secondIndex, firstObject_thirdIndex, secondObject_thirdIndex
0, 0, 100, 0, 0, 0
Up, Down, Up, Down, Up, Down...
How to create CSV Pattern above?
Thank you...
I think this will give you the result you want:
var objRow = [{
date: 2011-09-20,
nums: [0, 100, 0],
customerID: "C1101",
ANI: 1234
}, {
date: 2011-09-25,
nums: [0, 0, 0],
customerID: "C1101",
ANI: 1234
}, {
date: 2011-09-20,
nums: [0, 500, 0],
customerID: "C1102",
ANI: 5678
}, {
date: 2011-09-22,
nums: [0, 0, 50],
customerID: "C1102",
ANI: 5678
}];
//CREATE CSV-FORMATTED STRINGS
var csvLine = "";
var numsArray = new Array();
for (var i=0; i<objRow.length; i++) {
//check if this is the first element with a new 'ANI' (which means a new CSV line starts)
if (objRow[i-1]==(undefined||null) || objRow[i].ANI!=objRow[i-1].ANI) {
//if so, start a new string
csvLine = objRow[i].ANI +", "+ objRow[i].customerID +", "; //add the 'ANI' and 'customerID'
numsArray.length = 0; //clear array
numsArray.push(objRow[i].nums); //store the 'nums' in a separate array
} else {
//if not, add to the existing string
numsArray.push(objRow[i].nums); //store the 'nums' in a separate array
}
//check if this is the last element with the same 'ANI' (which means this CSV line is complete)
if (objRow[i+1]==(undefined||null) || objRow[i].ANI!=objRow[i+1].ANI) {
//add the 'nums' of every object in intertwining order (every 1st, every 2nd, etc.)
for (var k=0; k<numsArray[0].length; k++) {
for (var j=0; j<numsArray.length; j++) {
csvLine += numsArray[j][k].toString() +", ";
}
}
//remove the last comma
if (csvLine.substring(csvLine.length-2) == ", ") {
csvLine = csvLine.substring(0,csvLine.length-2);
}
//output the CSV line
document.getElementById("csv").innerHTML += csvLine + "<br />";
}
}
<div id="csv"></div>
(fiddle: http://jsfiddle.net/5gyp3ce6/16/)
I had to change your array a little bit, because for this to work, the array keys need to all be the same.
Also, I had to change the ID's to strings, otherwise they couldn't be defined.
Instead of writing it to the <div> at the end you can of course add the line to another variable of write it to file or whatever.
If the comments in the code aren't clear enough, just leave a comment and I'll try to explain it better.
Try
var objRow = [
{
"2011-09-20" : [0, 100, 0],
customerID : "C1101",
ANI : 1234
},
{
"2011-09-25" : [0, 0, 0],
customerID : "C1101",
ANI : 1234
},
{
"2011-09-20" : [0, 500, 0],
customerID : "C1102",
ANI : 5678
},
{
"2011-09-22" : [0, 0, 50],
customerID : "C1102",
ANI : 5678
}
];
var arr = [],
res = [],
csv = $.map(objRow, function (v, k) {
// items
arr.push(v.ANI, v.customerID, v[Object.keys(v)[0]]);
// arrays
var a = $.grep(arr, function (val, index) {
return $.isArray(val)
});
// strings
var s = arr.filter(function (i) {
return typeof i === "string"
});
// sort items
res.push([arr.filter(Number)[0]
, s[0]
, a.splice(0, 2).join(",")
, arr.filter(Number).slice(-1)[0]
, s.slice(-1)[0]
, a.join(",")]);
return res
}).slice(-1)[0];
// format text , html
csv = (csv.slice(0, 3) + "<br>" + csv.slice(-3))
.replace(/,/g, ", ");
$("body").append(csv)
var objRow = [
{
"2011-09-20" : [0, 100, 0],
customerID : "C1101",
ANI : 1234
},
{
"2011-09-25" : [0, 0, 0],
customerID : "C1101",
ANI : 1234
},
{
"2011-09-20" : [0, 500, 0],
customerID : "C1102",
ANI : 5678
},
{
"2011-09-22" : [0, 0, 50],
customerID : "C1102",
ANI : 5678
}
];
var arr = [],
res = [],
csv = $.map(objRow, function (v, k) {
arr.push(v.ANI, v.customerID, v[Object.keys(v)[0]]);
// arrays
var a = $.grep(arr, function (val, index) {
return $.isArray(val)
});
// strings
var s = arr.filter(function (i) {
return typeof i === "string"
});
res.push([arr.filter(Number)[0], s[0], a.splice(0, 2).join(","), arr.filter(Number).slice(-1)[0], s.slice(-1)[0], a.join(",")]);
return res
}).slice(-1)[0];
csv = (csv.slice(0, 3) + "<br>" + csv.slice(-3))
.replace(/,/g, ", ");
$("body").append(csv)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>