Problems with Arrays on Angular 5 - javascript

I have this problem:
I have a search in the component "Table" (PrimeNg).
This search is to start when I post a character in the input. The search is correct, but when I clean the entry, the values do not return. This line at the beginning is just for this "this.groupExamples = this.Examples group;" but apparently when I change the elements of an array the other is affected.
public getGrupoExames(){
this.serviceExames.getGrupoExames()
.subscribe((response)=> {
this.grupoExames = response;
this.grupoExamesAux = response;
}, (erro)=> {
console.log("Erro");
});
}
private filtarGrupoExames(event){
let filtro: GrupoExame[] = [];
this.grupoExames = this.grupoExamesAux.slice();
for(let i = 0; i < this.grupoExames.length; i++) {
let grupo = this.grupoExames[i];
let listaExames = [];
for(let j = 0; j < grupo.exames.length; j++){
let exame = grupo.exames[j];
if(exame.nome.toLowerCase().indexOf(event.toLowerCase()) == 0) {
listaExames.push(exame);
}
}
grupo.exames = listaExames;
filtro.push(grupo);
}
this.grupoExames = filtro;
}

I suppose that you display whatever is inside your grupoExames, if that is correct you can try this structure
if(event.target.value.length > 1) {
do the filter
}
else {
this.getGrupoExames();
}
Maybe another more ambiguous solution is to create a button to delete the filter and access to all the content .
Hope it helps you!

Related

Issues getting data from array's dictionary JS

I'm having issues to get the stored data in my array. I can't see where is the problem on my function and why is returning undefined elements.
This is the function where I store data in the array:
function getTaskKidData(str) {
var tasks = $('#tasks_data > div');;
var formated_tasks = [];
var formated_kids = [];
formated_homeworks = [];
tasks.each(function(index) {
var task_kids = $(this).find('ul').eq(0).find('li');
var task_homeworks = $(this).find('ul').eq(1).find('li');
if (task_kids.length > 0 && task_homeworks.length > 0) {
task_kids.each(function(index) {
var kid_name = $(this).text().trim();
if (str == "kid"){
var kid = $('#kid_list > li > a[class*="active"]').text().replace(window.location.pathname.split('/')[2],'').trim();
if (kid == kid_name){
formated_kids.push({'name': kid_name});
}
}else{
formated_kids.push({'name': kid_name});
}
});
task_homeworks.each(function(index) {
var homework_name = $(this).find('p').eq(0).text().trim();
var homework_date = $(this).find('p').eq(1).text().trim();
formated_homeworks.push({
'name': homework_name,
'date': homework_date,
});
});
formated_tasks.push({
'kids': task_kids,
'homeworks': task_homeworks,
})
}
});
return formated_tasks;
}
I don't understand why the objects in the output of the array are "li" tags if I'm storing data as text. The output of the array is the next one:
This is the code where I'm trying to get the data:
var tasks = getTaskKidData("kid");
console.log(tasks)
for (let i = 0; i < tasks.length; i++) {
console.log("schedule");
for (let j = 0; j < tasks[i]['kids'].length; j++) {
console.log(tasks[i]['kids'][j]['name']);
}
for (let j = 0; j < tasks[i]['homeworks'].length; j++) {
console.log(tasks[i]['homeworks'][j]['name']);
console.log(tasks[i]['homeworks'][j]['date']);
}
}
And this is the output when I run the code:
Any idea of the problem?
Thanks for reading!!
In your code you have
var task_kids = $(this).find('ul').eq(0).find('li');
and later you log task_kids. The log output shows li elements because that was what you selected.

Adding a running sum to a javascript object

I have a javascript object as below
var mydata=[
{"Club":"Blackburn","EventNo":1,"Pnts":3,"CumPnts":0},
{"Club":"Blackburn","EventNo":2,"Pnts":1,"CumPnts":0},
{"Club":"Blackburn","EventNo":3,"Pnts":4,"CumPnts":0},
{"Club":"Preston","EventNo":1,"Pnts":2,"CumPnts":0},
{"Club":"Preston","EventNo":2,"Pnts":4,"CumPnts":0},
{"Club":"Preston","EventNo":3,"Pnts":2,"CumPnts":0},]
I want to update the object so that CumPnts contains a running points total for each Club as below
{"Club":"Blackburn","EventNo":1,"Pnts":3,"CumPnts":3},
{"Club":"Blackburn","EventNo":2,"Pnts":1,"CumPnts":4},
{"Club":"Blackburn","EventNo":3,"Pnts":4,"CumPnts":8},
{"Club":"Preston","EventNo":1,"Pnts":2,"CumPnts":2},
{"Club":"Preston","EventNo":2,"Pnts":4,"CumPnts":6},
{"Club":"Preston","EventNo":3,"Pnts":1,"CumPnts":7},]
Any help would be much appreciated
Here is a function that loops through the list and updates it after it's been added. But I suspect that the events come in one at a time so there could be another function that can look the cumPtns obj and take from that. Here is for the current list.
var cumData = {};
var mydata=[
{"Club":"Blackburn","EventNo":1,"Pnts":3,"CumPnts":0},
{"Club":"Blackburn","EventNo":2,"Pnts":1,"CumPnts":0},
{"Club":"Blackburn","EventNo":3,"Pnts":4,"CumPnts":0},
{"Club":"Preston","EventNo":1,"Pnts":2,"CumPnts":0},
{"Club":"Preston","EventNo":2,"Pnts":4,"CumPnts":0},
{"Club":"Preston","EventNo":3,"Pnts":2,"CumPnts":0}];
function updateMyData() {
for (var i = 0; i < mydata.length; i++) {
var item = mydata[i];
if(cumData[item.Club] == undefined) {
cumData[item.Club] = {};
cumData[item.Club] = item.Pnts;
} else {
cumData[item.Club] = cumData[item.Club] + item.Pnts;
}
mydata[i].CumPnts = cumData[item.Club];
};
console.log(mydata);
//if you want to return it you can have this line below. Otherwise the object is updated so you'll probably want to do something with it once it's updated. Call back maybe?
return mydata;
}
updateMyData();
The first time it encounters a team it adds it to an array and so does with the corresponding cumPnts, so we can keep track of whether we checked a team earlier or not.
var tmArr = [];
var cumArr = [];
for(var i = 0; i < mydata.length; i++) {
var elm = mydata[i];
var club = elm.Club;
var points = elm.Pnts;
var idx = tmArr.indexOf(club);
if(idx > -1) {
cumArr[idx] += points;
elm.CumPnts = cumArr[idx];
}
else {
elm.CumPnts = points;
tmArr[tmArr.length] = club;
cumArr[cumArr.length] = points;
}
}
jsfiddle DEMO

JavaScript look match substring in query with object

I would like to display a message on the page based on some value appearing in the URL. I have a known list of strings I'm looking for and the corresponding message. I cannot seem to get anywhere with the lookup / messaging. Could anyone pls kindly help? JavaScript only preferred, not jquery. Not that I the difference at this point ;)
Many thanks!
<div id="messagediv"></div>
Sample URLs to test:
<p>Campaign 1
<p>Campaign 2
<p>Campaign 3
<script>
(function () {
var params = window.location.search.substring(1).split('&'),
urlParams = {},
key, val;
for (var i = 01; i < params.length; i++) {
urlParams[params.split('=')[0]] = params.split('=')[1];
}
// querystring is ?utm_campaign=SpaCamp12458
// for instance, match URL query value SpaCamp12458 with the nums SpaComp key and show the corresponding text in the messagediv
var nums = {
defaultMessage: "Default Message",
"SpaComp": "Spas",
"PoolComp": "Recreation",
"BeachComp": "Outdoors"
}
for (var i in nums) {
if (nums.hasOwnProperty(i)) {
var found = false;
for (var j in urlParams) {
if (urlParams.hasOwnProperty(j)) {
if (urlParams[j].indexOf(nums[i]) === 0) {
document.getElementById("messagediv").innerHTML = nums[i];
found = true;
break;
}
}
}
if (!found) {
document.getElementById("messagediv").innerHTML = nums.defaultMessage;
}
}
}
})();
</script>

Merging arrays in JavaScript not working

When I try var a = ar_url2.concat(ar_desc2); to join my arrays into one it returns null. I'm sure it's trivial but I spent a few hours stuck on this now and an explanation as why this is happening would be great. In my code bellow I tried while(ar_url2.length)a.push(ar_url2.shift()); and it returns same null...
function agregar() {
var i = 0,
textarea;
var ar_desc = [];
while (textarea = document.getElementsByTagName('textarea')[i++]) {
if (textarea.id.match(/^desc_([0-9]+)$/)) {
ar_desc.push(textarea.id);
}
}
var desc_count_demo = document.getElementById('desc_count').value;
var desc_count = desc_count_demo - 1;
i = 0;
var ar_desc2 = [];
var campo = null;
while (i <= desc_count) {
campo = document.getElementById(ar_desc[i]).value;
ar_desc2[ar_desc[i]] = campo;
i++;
}
i = 0;
var input;
var ar_url = [];
while (input = document.getElementsByTagName('input')[i++]) {
if (input.id.match(/^url_([0-9]+)$/)) {
ar_url.push(input.id);
}
}
var url_count_demo2 = document.getElementById('url_count').value;
var url_count2 = url_count_demo2 - 1;
i = 0;
var ar_url2 = [];
while (i <= url_count2) {
campo = document.getElementById(ar_url[i]).value;
ar_url2[ar_url[i]] = campo;
i++;
}
// var a = Array.prototype.concat.call(ar_url2, ar_desc2);
while (ar_url2.length) a.push(ar_url2.shift());
function url(data) {
var ret = [];
for (var d in data)
ret.push(encodeURIComponent(d) + "=" + encodeURIComponent(data[d]));
return ret.join("&");
}
window.open('alta1.php?'+url(a));
}
EDIT: If I pass to function url(ar_url2) or url(ar_desc2) the returned values in the URL are
http://localhost/proj1/alta1.php?url_0=inpit&url_1=input
and
http://localhost/proj1/alta1.php?desc_0=input&desc_1=input
But still cannot merge both into one...
One thing I see is your ar_url Array is filled by:
while(input=document.getElementsByTagName('input')[i++]){
if(input.id.match(/^url_([0-9]+)$/)){
ar_url.push(input.id);
}
}
Since you the putting the whole id in the array, it will be filled with things like: 'url_0', 'url_1', 'url_2', etc...
Later you do:
ar_url2[ar_url[i]] = campo;
When you index into ar_url, you get out the 'url_XXX' strings. That means you are setting the 'url_XXX' properties on ar_url2 instead of filling in the elements of the array.
Try changing your second loop to:
while(input=document.getElementsByTagName('input')[i++]){
var result;
if(result = input.id.match(/^url_([0-9]+)$/)){
ar_url.push(+result[1]);
}
}
To use the value captured in the ([0-9]+) portion of the RegExp instead of the entire 'url_XXX' string.

Using separators in JS

I'm currently writing a program that uses ";" as a seperator and extracts the url up until that point upon searching the content.
So it has the format:
name;surname
In searching the given arrays... I decided to go the extra mile and test for arrays without the ";" but this has confused the program - it has no idea of the ";" position anymore and this throws a spanner in the works!
Here is my code so far - many thanks in advance!
pages =
[
"The first", "An;alternative;page", "Yet another page"
]
u_c_pages =
[
"www.cam.ac.uk;"+pages[0]
,
"www.warwick.ac.uk"+pages[1]
,
"www.kcl.ac.uk;"+pages[1]
,
"www;"+pages[2]
]
var pattern5 = prompt('5) Please enter a search term:');
function url1_m1(u_c_pages,pattern)
{
var seperator = [];
var seperatorPos = [];
if(pattern)
{
for (var i = 0; i < u_c_pages.length; i++)
{
var found = true;
if((u_c_pages[i].indexOf(";"))<0)
{
found=false;
}
else
{
seperator[seperator.length] = i;
seperatorPos[seperatorPos.length] = (u_c_pages[i].indexOf("|"));
}
}
if(seperator.length==0)
{
return("Nothing found!");
}
else
var found2 = "";
{
for (var j = 0; j < seperator.length; j++)
{
if(u_c_pages[j].substring(seperatorPos[j],u_c_pages[j].length-1).toLowerCase().indexOf(pattern.toLowerCase()) >= 0)
{
found2 = (u_c_pages[j].substring(0,seperatorPos[j]));
break;
}
}
return(found2)
}
}
else
{
// only returned when the user decides to type in nothing
return("Nothing entered!");
}
}
alert(url1_m1(u_c_pages,pattern5));
enjoy the power of regex:
on JSFiddle
pages = ["The first", "An;alternative;page", "Yet another page"];
u_c_pages = [
"www.lboro.ac.uk;"+pages[0],
"www.xyz.ac.uk;"+pages[1],
"www.xyz.ac.uk;"+pages[1],
"www;"+pages[2]
];
var pattern5 = prompt('5) Please enter a search term:');
function url1_m1(u_c_pages,pattern)
{
// escape search pattern
pattern = pattern.toLowerCase().replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&')
pattern = new RegExp('^([^;]+);.*?' + pattern, 'i');
var result = null;
for(var i=0;i<u_c_pages.length;i++) {
if((result = u_c_pages[i].match(pattern))) {
return result[1];
}
}
return false;
}
alert(url1_m1(u_c_pages,pattern5));
You can use String.split(";") to split a string into segments. The parameter is the seperator.

Categories