Count how many times i have the same word - javascript

My variable tag returns one of these 4 different values: assistance, bug, evolution or maintenance. I would like to count how many times I have each of those words. I would like to display how many times I have each of those item in my console first. I really don't know how to do that. Here is my code :
function displaytickets(y){
$.ajax({
url: "https://cubber.zendesk.com/api/v2/users/" + y + "/tickets/requested.json?per_page=150",
type: 'GET',
dataType: 'json',
cors: true ,
contentType: 'application/json',
secure: true,
beforeSend: function(xhr) {
xhr.setRequestHeader ("Authorization", "Basic " + btoa(""));
},
success: function(data) {
var sortbydate = data.tickets.sort(function(a, b){
return new Date(b.created_at) - new Date(a.created_at);
});
var ids = $.map(data.tickets, function (data) {
return data.id;
})
localStorage.setItem("mesid", ids);
for (i = 0; i < data.tickets.length; i++) {
var myticket = data.tickets[i];
var mydate = data.tickets[i].created_at;
var created = moment(mydate).format("MM-DD-YY");
var mytitle = data.tickets[i].subject;
var description = data.tickets[i].description;
var status = data.tickets[i].status;
var tag = data.tickets[i].tags[0];
console.log(tag);
var myid = data.tickets[i].id;
}
var nbticket = data.tickets.length;
$("#name").append('<h2 class="title">' + " " + nbticket + " ticket(s)" + '</h2>');
},
});
}
Here's what I get from the console for the console.log(tag):

You can achieve this by using an object to store the occurrence count, keyed by the string itself. Try this:
var occurrences = {};
Then in your success handler you can add and increment the tags as you find them:
success: function(data) {
// your code here...
for (i = 0; i < data.tickets.length; i++) {
// your code here...
var tag = data.tickets[i].tags[0];
if (occurrences.hasOwnProperty(tag)) {
occurrences[tag]++;
} else {
occurrences[tag] = 1;
}
}
console.log(occurrences);
},
Working example

Did you try to count it in your for loop ?
var maintenance_counter = 0;
for (i = 0; i < data.tickets.length; i++) {
var myticket = data.tickets[i];
var mydate = data.tickets[i].created_at;
var created = moment(mydate).format("MM-DD-YY");
var mytitle = data.tickets[i].subject;
var description = data.tickets[i].description;
var status = data.tickets[i].status;
var tag = data.tickets[i].tags[0];
var myid = data.tickets[i].id;
if( tag == "maintenance" ){
maintenance_counter++;
}
}
alert("Total maintenance occurrence:"+ maintenance_counter);

Create an object to hold your tag result count, similar to this:
var tagCount = {};
for (i = 0; i < data.tickets.length; i++) {
var tag = data.tickets[i].tags[0];
if (tagCount[tag] === undefined) {
tagCount[tag] = 1;
} else {
tagCount[tag] += 1;
}
}
console.log(tagCount);

Related

For loop not iterating a variable

I'm just learning javascript and I'm trying to update woocommerce products through GAS.
The issue in question is the following:
I have a variable that parses the response from woocommerce
for (let sku of skuSearch) {
var surl = website + "/wp-json/wc/v3/products?consumer_key=" + ck + "&consumer_secret=" + cs + "&sku=" + sku;
var url = surl
Logger.log(url)
var result = UrlFetchApp.fetch(url, optionsGet);
if (result.getResponseCode() == 200) {
var wooProducts = JSON.parse(result.getContentText());
Logger.log(result.getContentText());
}
Then I have another for to iterate and from a new array that contains id + sku of wooProducts and price from a different variable that takes the updated price from my sheet:
var idLength = wooProducts.length;
Logger.log(idLength);
for (var i = 0; i < idLength; i++) {
var container = [];
Logger.log(i);
container.push({
id: wooProducts[i]["id"],
sku: wooProducts[i]["sku"],
price: data[i]["price"],
});
I can't tell exactly why it doesn't work. I mean the for loop works, it pushes id, sku and price in every loop, it's just that data[i] only provides the first ¿object? instead of looping like wooProducts which add +1 at every loop.
I'll copy 3 loops so it's crystal clear, I'm not sure it's already clear.
Loop 1:
[{"id":1622,"sku":"PD-1000-B","price":8145.9}]
Loop 2:
[{"id":1624,"sku":"PD-1007-A","price":8145.9}]
Loop 3:
[{"id":1625,"sku":"PD-1014","price":8145.9}]
As you can see id+sku change but price doesn't.
For further context, I'll include the data variable that is declaed outside the For:
const data = codigos.map(function(codigos, indice) {
return {
sku: codigos[0],
price: precios[indice][0]
}
})
//** EDIT:
I'm adding the entire code so it makes more sense maybe?
function getDataloopwoo() {
var ck = 'xxx'
var cs = 'xxx'
var website = 'xxx'
var optionsGet =
{
"method": "GET",
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
"muteHttpExceptions": true,
};
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('PreciosBULK');
var codigos = sheet.getRange("A2:A").getValues();
var precios = sheet.getRange("B2:B").getValues();
var skuSearch = sheet.getRange("A2:A").getValues();
const data = codigos.map(function(codigos, indice) {
return {
sku: codigos[0],
price: precios[indice][0]
}
})
Logger.log(skuSearch)
for (let sku of skuSearch) {
var surl = website + "/wp-json/wc/v3/products?consumer_key=" + ck + "&consumer_secret=" + cs + "&sku=" + sku;
var url = surl
Logger.log(url)
var result = UrlFetchApp.fetch(url, optionsGet);
if (result.getResponseCode() == 200) {
var wooProducts = JSON.parse(result.getContentText());
Logger.log(result.getContentText());
}
var idLength = wooProducts.length;
Logger.log(idLength);
var container = [];
for (var i = 0; i < idLength; i++) {
Logger.log(i);
container.push({
id: wooProducts[i]["id"],
sku: wooProducts[i]["sku"],
price: data[i]["price"],
});
Logger.log(container);
var wooBatch = JSON.stringify(container);
Logger.log(wooBatch);
}
}
}
// FINAL EDIT with "solve":
So I figured it was inefficient to ask by 1 sku at a time, so now I'm asking by the 100, and paginating with a while if and saving id, sku, price to the container array.
I will need now to compare the container array to the array with the updated prices and form a new array with id, sku and updated price, I'm reading up on that right now. The code:
function getDataloopwoo() {
var ck = 'xx'
var cs = 'xx'
var website = 'xx'
var optionsGet =
{
"method": "GET",
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
"muteHttpExceptions": true,
};
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('PreciosBULK');
var codigos = sheet.getRange("A2:A").getValues();
var precios = sheet.getRange("B2:B").getValues();
const data = codigos.map(function(codigos, indice) {
return {
sku: codigos[0],
price: precios[indice][0]
}
})
var container = [];
var surl = website + "/wp-json/wc/v3/products?consumer_key=" + ck + "&consumer_secret=" + cs + "&per_page=100";
var url = surl
//Logger.log(url)
var result = UrlFetchApp.fetch(url, optionsGet);
var headers = result.getAllHeaders();
var total_pages = headers['x-wp-totalpages'];
var pages_count = 0;
while (pages_count < total_pages) {
if (result.getResponseCode() == 200) {
var wooProducts = JSON.parse(result.getContentText());
//Logger.log(result.getContentText());
}
for (var i = 0; i < wooProducts.length; i++) {
//Logger.log(i);
container.push({
id: wooProducts[i]["id"],
sku: wooProducts[i]["sku"],
price: wooProducts[i]["price"],
});
Logger.log(container);
}
pages_count++;
if (pages_count < total_pages){
var surl = website + "/wp-json/wc/v3/products?consumer_key=" + ck + "&consumer_secret=" + cs + "&per_page=100" + "&page=" + (pages_count + 1);
var url = surl
var result = UrlFetchApp.fetch(url, optionsGet);
Logger.log(url);
}
}
}
You're reseting the array container in every iteration of the loop:
for (var i = 0; i < idLength; i++) {
var container = []; // <-----------------here
...
container.push({
...
I think the array should be defined outside the loop:
var container = [];
for (var i = 0; i < idLength; i++) {
...
container.push({
...

document.getElementsByClassName(...)[0] not working

I'm making site in which I have to add some element but only when they contain class .addEvent but when I try document.getElementsByClassName(json[i].date)[0].classList.contains("addEvent")
It shows me this error in console (json[i].date is something like: 2019-11-06):
TypeError: document.getElementsByClassName(...).classList is undefined
And when I display date in console it shows as it should be.
Here is my whole javascript code, maybe it would help:
$(() => {
var event;
$.ajax({
type: "GET",
url: "getEvents.php",
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function(json) {
for (var i = 0; i < json.length; i++) {
console.log(document.getElementsByClassName(json[i].date)[0].classList.contains("addEvent"));
if (document.getElementsByClassName(json[i].date)[0].classList.contains("addEvent")) {
document.getElementsByClassName(json[i].date)[0].innerHTML += " <br/><span class='event'>" + json[i].name + "<br/>" + json[i].place + "</span>";
document.getElementsByClassName(json[i].date)[0].style.backgroundColor = json[i].color;
document.getElementsByClassName(json[i].date)[0].style.color = "#ffffff";
document.getElementsByClassName(json[i].date)[0].style.fontWeight = "bold";
document.getElementsByClassName(json[i].date)[0].style.opacity = "0.6";
}
}
},
error: function(error) {
alert("error");
console.log(error);
}
});
var day;
var shown = false;
$("td.addEvent").click(function() {
if (shown == false) {
$(".addEventMenu").css("display", "block");
day = getDay($(this));
var clickedDay = document.getElementsByTagName("p");
clickedDay[1].innerHTML += day;
shown = true;
}
});
function getDay(input) {
return input.clone().children().remove().end().text();
}
$("button.addEventBtn").click(function(e) {
e.preventDefault();
var year;
var month = $(".month").val();
const regex = /[0-9]{4}/gm;
let m;
while ((m = regex.exec($(".date").text())) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
year = `${match}`;
});
}
var name = $(".eventName").val();
var description = $(".eventDescription").val();
var place = $(".eventPlace").val();
var startHour = $('.eventStartHour').val();
var endHour = $('.eventEndHour').val();
var color = $('.eventColor').val();
var userId = $('input.userId').val();
if (day < 10) {
day = "0" + day;
}
var date = year + "-" + month + "-" + day;
$.ajax({
url: 'addEvent.php',
data: {
'eventName': name,
'eventDescription': description,
'eventPlace': place,
'eventStartHour': startHour,
'eventEndHour': endHour,
'eventColor': color,
'eventDate': date,
'userId': userId
},
type: 'post',
success: function(data) {
},
error: function(request, status, error) {
alert(request, status);
}
});
});
$("p.closeEventMenu").click(function() {
$(".addEventMenu").css("display", "none");
var clickedDateDay = $("p.clickedDay").text();
clickedDateDay = clickedDateDay.replace(/\s+$/, '');
$("p.clickedDay").text(clickedDateDay.substring(0, clickedDateDay.length - 2));
shown = false;
});
});
You are not confirming that the element exists before trying to use it.
if (document.getElementsByClassName(json[i].date)[0].classList.contains("addEvent"))
If no elements matching class json[i].date exist, this if will throw the exception.
You should confirm the selector is returning elements before trying to use any of them:
var elements = document.getElementsByClassName(json[i].date);
if(elements.length > 0 && elements[0].classList.contains("addEvent"))
This will confirm the element actually exists before attempting to gather any information (classList) from the element. Of course, whether or not the element exists depends on many other factors - but in this case it seems that there are not any elements matching the selector on the page.

jquery click event for child div not working in plugin

I'm trying to add a click event on each row. On click I need to be able to grab the name (ex. Jeremy) and place in the top div, replacing the question marks. My click event only works on id="data" but not the child divs. I have my code here on codepen as well http://codepen.io/rrschweitzer/pen/GrRyLg?editors=0110. Any help is much appreciated!!
This is my html:
<div id="interview-test">
<div class="top-bars">
<div id="secret">???</div>
<button id="clear">Clear</button>
</div>
<div id="data"></div>
</div>
This is my Jquery:
(function($) {
$.fn.interviewTest = function() {
var self = this;
var testData = null;
var url = "https://private-f3b4b-interview2.apiary-mock.com/data";
// create rows
self.createRow = function(data) {
var theRow = $('<div>').addClass('rows')
.append($('<div>').addClass('image-container')
.append($('<img>').addClass('picture').attr('src', data.image)))
.append($('<div>').addClass('name').append($('<h1>').html(data.name)))
.append(self.getDate(data.timestamp))
return theRow;
}
self.getDate = function(date) {
var date = date.slice(0,-3)
var newdate = new Date(date * 1000)
var year = newdate.getFullYear();
var month = newdate.getMonth();
var day = newdate.getDay()
var formattedDate = month + '/' + day + '/' + year
return formattedDate;
}
// api call
$.ajax({
beforeSend: function(xhr) {
xhr.setRequestHeader('Authorization', 'Basic ');
},
url: url,
success: function(data, status) {
var dataObject = data;
var i = 0;
var testData = [];
for(var key in dataObject) {
testData[i] = dataObject[key]
i++;
}
// console.log(testData);
self.createDataList(testData, i);
}
})
self.createDataList = function(data, size) {
var rows = $(self).find('#data');
if (size != 0) {
$.each(data, function(key, value) {
// console.log(value)
rows.append(self.createRow(value))
})
}
}
// event listeners
$(self).find('.rows').on('click', function(e) {
var current = $(e.currentTarget);
console.log(current);
// if(current)
})
}}(jQuery))$('#interview-test').interviewTest();
You need to add your event listeners after elements (rows) are created:
(function($) {
$.fn.interviewTest = function() {
var self = this;
var testData = null;
var url = "https://private-f3b4b-interview2.apiary-mock.com/data";
// create rows
self.createRow = function(data) {
var theRow = $('<div>').addClass('rows')
.append($('<div>').addClass('image-container')
.append($('<img>').addClass('picture').attr('src', data.image)))
.append($('<div>').addClass('name').append($('<h1>').html(data.name)))
.append(self.getDate(data.timestamp))
return theRow;
}
self.getDate = function(date) {
var date = date.slice(0,-3)
var newdate = new Date(date * 1000)
var year = newdate.getFullYear();
var month = newdate.getMonth();
var day = newdate.getDay()
var formattedDate = month + '/' + day + '/' + year
return formattedDate;
}
// api call
$.ajax({
beforeSend: function(xhr) {
xhr.setRequestHeader('Authorization', 'Basic ');
},
url: url,
success: function(data, status) {
var dataObject = data;
var i = 0;
var testData = [];
for(var key in dataObject) {
testData[i] = dataObject[key]
i++;
}
// console.log(testData);
self.createDataList(testData, i);
}
})
self.createDataList = function(data, size) {
var rows = $(self).find('#data');
if (size != 0) {
$.each(data, function(key, value) {
// console.log(value)
rows.append(self.createRow(value))
});
self.addEventListeners()
}
}
self.addEventListeners() {
// event listeners
$(self).find('.rows').on('click', function(e) {
var current = $(e.currentTarget);
console.log(current);
// if(current)
})
}
}}(jQuery))$('#interview-test').interviewTest();
you can use event delegation for this to attach the event with the parent element which will fire for all the matching selector child elements.
$(self).on('click', ".rows",function(e) {
var current = $(this);
if(current)
{
var name = current.find(".name").text();
$("#secret").text(name);
}
})
code pen : http://codepen.io/anon/pen/EZxRwM?editors=0110
Your demo doesn't work however looking at your code you are trying to look for self.find('.rows') before the ajax has completed and the rows have been created
You either need to delegate the event or wait until rows are added in the ajax success

how to display json resful data using javascript or jquery

how do i display all content in my data array without repeating my self like i have done below .
// Program guide Rest
$(document).ready(function() {
$.ajax({
cache: false,
url: "http://engrid2media.com/nextt/api/epg/schedule/id/",
type: 'GET',
crossDomain: true,
dataType: 'json',
success: function() {
alert("EPG Success");
},
error: function() {
alert('EPG Failed!');
},
}).then(function(data) {
var result = data [0];
console.log(result);
$('.ch-name').append(result.ch_name);
$('.ch-logo').append(result.ch_logo);
$('.ch-desc').append(result.ch_desc);
$('.ch-genre').append(result.ch_genre);
$('.ch-type').append(result.type);
$('.ch-resolution').append(result.resolution);
var result1 = data [1];
console.log(result1);
$('.ch-name1').append(result1.ch_name);
$('.ch-logo1').append(result1.ch_logo);
$('.ch-desc1').append(result1.ch_desc);
$('.ch-genre1').append(result1.ch_genre);
$('.ch-type1').append(result1.type);
$('.ch-resolution1').append(result1.resolution);
var result2 = data [2];
console.log(result2);
$('.ch-name2').append(result2.ch_name);
$('.ch-logo2').append(result2.ch_logo);
$('.ch-desc2').append(result2.ch_desc);
$('.ch-genre2').append(result2.ch_genre);
$('.ch-type2').append(result2.type);
$('.ch-resolution2').append(result2.resolution);
var result3 = data [3];
console.log(result3);
$('.ch-name3').append(result3.ch_name);
$('.ch-logo3').append(result3.ch_logo);
$('.ch-desc3').append(result3.ch_desc);
$('.ch-genre3').append(result3.ch_genre);
$('.ch-type3').append(result3.type);
$('.ch-resolution3').append(result3.resolution);
var result4 = data [4];
console.log(result4);
$('.ch-name4').append(result4.ch_name);
$('.ch-logo4').append(result4.ch_logo);
$('.ch-desc4').append(result4.ch_desc);
$('.ch-genre4').append(result4.ch_genre);
$('.ch-type4').append(result4.type);
$('.ch-resolution4').append(result4.resolution);
var result5 = data [5];
console.log(result5);
$('.ch-name5').append(result5.ch_name);
$('.ch-logo5').append(result5.ch_logo);
$('.ch-desc5').append(result5.ch_desc);
$('.ch-genre5').append(result5.ch_genre);
$('.ch-type5').append(result5.type);
$('.ch-resolution5').append(result5.resolution);
});
});
This works fine , but it will be difficult to display over 20 items from the database with this method since i would have to do it one after the other.
A simple for loop would do it.
.then(function(data) {
for (var i = 0; i < 6; ++i)
{
var prefix = (i == 0 ? "" : i.toString());
$('.ch-name' + prefix).append(data[i].ch_name);
$('.ch-logo' + prefix).append(data[i].ch_logo);
$('.ch-desc' + prefix).append(data[i].ch_desc);
$('.ch-genre' + prefix).append(data[i].ch_genre);
$('.ch-type' + prefix).append(data[i].type);
$('.ch-resolution' + prefix).append(data[i].resolution);
}
});
Why not just write helper function?
Something like that.
function(data) {
var result,
suffix = '';
for (var i in data) {
result = data[i];
if (i > 0) {
suffix = i;
}
$('.ch-name' + suffix).append(result.ch_name);
$('.ch-logo' + suffix).append(result.ch_logo);
$('.ch-desc' + suffix).append(result.ch_desc);
$('.ch-genre' + suffix).append(result.ch_genre);
$('.ch-type' + suffix).append(result.type);
$('.ch-resolution' + suffix).append(result.resolution);
}
}
Try utilizing $.each()
$.each(data, function(key, val) {
var idx = key === 0 ? "" : key;
$(".ch-name" + idx).append(val.ch_name);
$(".ch-logo" + idx).append(val.ch_logo);
$(".ch-desc" + idx).append(val.ch_desc);
$(".ch-genre" + idx).append(val.ch_genre);
$(".ch-type"+ idx).append(val.type);
$(".ch-resolution" + idx).append(val.resolution);
});

Synchronous javascript does not work

I have a script which generates an array of audio files to be played on the click of a button. I am trying to use synchronous JS in order to change the values of some global variables and have been testing for changes with alerts but I get 'undefined' as a result (or my popups do not show).
My code:
jQuery.ajaxSetup({async:false});
var s;
var group;
var curr_rec;
var curr_start = 1;
var curr_end;
var curr_s_obj;
var recs;
var sync = new Array();
var sync_group = new Array();
var check_rec;
var check_id;
var check_start;
var check_end;
var loaded = 0;
var s_obj;
function compare(a,b){
if(a.fields.start_time<b.fields.start_time)
return -1;
if(a.fields.start_time>b.fields.start_time)
return 1;
return 0;
}
function process_data(recs){
for(var i=0;i<recs.length;i++){
check_rec = recs[i];
check_id = check_rec.fields.file_ID;
check_start = check_rec.fields.start_time;
check_end = check_rec_fields.end_time;
if((curr_start.getTime() <= check_start.getTime() && check_end.getTime()<= curr_end.getTime()) ||
(curr_start.getTime()>=check_start.getTime() && curr_start.getTime()<=check_end.getTime()) ||
(curr_end.getTime()>=check_start.getTime() && curr_end.getTime()<=check_end.getTime())
)
{
//diff = (check_start.getTime() - curr_start.getTime())/1000;
//check_rec["difference"] = diff;
sync.push(check_rec);
}
}
}
function load_data(sync){
var diff;
var last = sync[sync.length-1];
for(var j=0;j<sync.length-1;j++){
s_obj = new buzz.sound(sync[i].fields.rec_file);
sync_group.push(s_obj);
diff = (last.fields.start_time.getTime() - sync[i].fields.start_time.getTime())/1000;
if(diff>=0){
s_obj.setTime(diff);
}
else{
alert("error");
}
}
loaded = 1;
}
function synchronise(id){
$.ajax({
type:"GET",
url:"/webapp/playSound:" + id,
success: function(data){
curr_rec = eval("(" + data + ")");
curr_start = curr_rec.fields.start_time;
curr_end= curr_rec.fields.end_time;
curr_s_obj = new buzz.sound(curr_rec.fields.rec_file);
});
alert("ggo");
$.ajax(
type:"GET",
url:"/webapp/getRecs",
success: function(data){
recs = eval("("+ data +")");
process_data(recs);
});
alert(curr_start);
sync = sync.sort(compare);
load_data(sync);
var s1 = new buzz.sound( "../../static/data/second_audio.ogg");
s = new buzz.sound( "../../static/data/" + id +".ogg"); //curr_rec.fields.rec_file
/*
sync_group.push(s);
s.setTime(20.5);
sync_group.push(s1);
*/
group = new buzz.group(sync_group);
}
function playS(id){
if(loaded==0)
synchronise(id);
group.togglePlay();
}
function stopS(){
group.stop();
}

Categories

Resources