javascript: limit number of items - javascript

sorry but I'm new in javascrit.
I'm writing a simple rss reader, but I want to limit the number of feeds to 5 items, because the my target site can have 100 or more.
Here the code:
$("#mainPage").live("pageinit", function () {
$("h1", this).text(title);
$.get(RSS, {}, function (res, code) {
var xml = $(res);
var items = xml.find("item");
var items = $items.length && i < 5; i++); // here the problem!!
var entry = "";
$.each(items, function (i, v) {
entry = {
title:$(v).find("title").text(),
link:$(v).find("link").text(),
description:$.trim($(v).find("encoded").text()),
category:$.trim($(v).find("category").text()),
date:$(v).find("pubDate").text().substr(0,16),
autor:$(v).find("creator").text()
};
entries.push(entry);
});
var s = '';
$.each(entries, function(i, v) {
s += '<li>' + v.title + '<br><i>' + v.autor + ' - ' + v.date + '</i></li>';
});
$("#linksList").append(s);
$("#linksList").listview("refresh");
});
});
The problem is that when I try to limit the number of items adding
var items = $items.length && i < 5; i++);
the javascript stop to works. :-(
How to do it?

var items = $items.length && i < 5; i++); is invalid I think you want to
var items = items.slice(0, 4); is what you want.
https://api.jquery.com/slice/ (as pointed out to me, it's a jQuery object)
The jQuery object itself behaves much like an array; it has a length
property and the elements in the object can be accessed by their
numeric indices [0] to [length-1]. Note that a jQuery object is not
actually a Javascript Array object, so it does not have all the
methods of a true Array object such as join().
Because Javascript is 0-based (starts to count from 0) you want element 0 to 4, in order to get the first 5 elements.

You can use lt(n) function
var items = xml.find("item:lt(5)");

Related

Count occurrences from object

Im making an api call and sorting data that I wanted from it. The only problem is that I have to count the date existed.
Currently I have successfully displayed the data that I want. Which looks like this.
2017-06-09T17:49:49.975+12:00
2017-07-13T08:59:20.023+12:00
2017-05-29T14:17:18.148+12:00
2017-05-21T22:19:07.951+12:00
2017-06-09T13:59:50.464+12:00
2017-06-13T08:18:30.340+12:00
2017-07-27T12:41:17.423+12:00
Now I want to count how many has the same dates. Format would be something like,
{ date = 2017-06-09T17:49:49.975+12:00, count = 2, date = 2017-07-13T08:59:20.023+12:00, count = 1... and so on... }
I've tried few codes from here which didn't work for me.
Here's what I tried recently,
https://codepen.io/anon/pen/gxyZXm
Here is my version of the solution.
Codepen Demo
JS:
console.clear();
var counters = [];
$.ajax({
async: true,
 dataType: "json",
 url: "https://api.myjson.com/bins/n1cwx",
 success: function(data) {
   $.each(data, function (i, object) {
console.log(object.last_activity_at);
if (!object.last_activity_at) return;
var count= 0;
var arr = [];
for (var key in data){
var date1 = new Date(data[key].last_activity_at).setHours(0,0,0,0);
var date2 = new Date(object.last_activity_at).setHours(0,0,0,0);
if(date1 === date2){
count += 1;
}
};
$("body").append("<p>" + count + "</p>");
console.log(count);
console.log(arr);
$("body").append("<p>" + object.last_activity_at + "</p>");
});
 }
});
I've updated your pen to work somewhat, here's the key thing I did.
Count the occurrences of each timestamp
let keys = Object.keys(data)
let dateCount = keys.reduce((acc, val) => {
if (data[val].created_at in acc) {
acc[data[val].created_at]++
} else {
acc[data[val].created_at] = 1
}
return acc
}, {})
dateCount now has the amount of times each date appeared. From there, it's pretty simple. I create a count variable that grabs the count, or if it doesn't exist, set it to 0.
   $.each(data, function (i, object) {
if (!object.last_activity_at) return;
const count = dateCount[object.last_activity_at] ? dateCount[object.last_activity_at] : 0
$("body").append("<p>" + object.last_activity_at + " " + count + "</p>");
https://codepen.io/anon/pen/brXLOM?editors=0010
Simply do this:
var counts = {};
dateArray.forEach(function(x) {
counts[x] = (counts[x] || 0) + 1;
});
console.log(counts);
Keep inner loop to outside of loop like below
// initialize the counters outside of the loop
var counters = [];
$.each(data, function (i, object) {
if (!object.last_activity_at) return true;
counters[object] =counters[object] ? counters[object] + 1 : 1;
});
// keep next loop out side because you will get multiple line of same date with different number
// now returning the same kind of dates
var keys = Object.keys(counters);
$(keys).each(function(index,key){
$("body").append("<p> "+key+":" + counters[key] + "</p>");
})

JS how to Sum/Average?

I have an object and need to sum/average of each dynamic span. Can't seem to convert those to numbers though. Please Help.
Console Log
Code Sample
Expand/Collapse Created : 1/3/2017 ‎<span>(10)‎</span>
Expand/Collapse Created : 1/4/2017 ‎<span>(38)‎</span>
Expand/Collapse Created : 1/5/2017 ‎‎<span>(13)</span>
Expand/Collapse Created : 1/6/2017 ‎‎<span>(35)</span>
Expand/Collapse Created : 1/9/2017 ‎‎<span>(46)</span>
Expand/Collapse Created : 1/10/2017 ‎‎<span>(17)</span>
Expand/Collapse Created : 1/11/2017 ‎‎<span>(27)</span>
var arr = [];
$(".ms-gb span").each(function(index, elem){
arr.push($(this).text());
});
$("#result").text(arr.join("+")); // (10)+‎(38)+‎(13)+‎(35)+‎(46)+‎(17)+‎(27)
var allNumbers = document.getElementById('result').innerText; // (10)+‎(38)+‎(13)+‎(35)+‎(46)+‎(17)+‎(27)
allNumbers = allNumbers.replace(/["'()]/g,""); // ‎‎10+‎38+‎13+‎35+‎46+‎17+‎28
var newString = allNumbers.split("+"); // Object - ["‎10", "‎38", "‎13", "‎35", "‎46", "‎17", "‎27"]
well you're pretty close. i'd recommend using the reduce function
var sum = allNumbers.reduce(function(a,b){ return +a + +b; }, 0)
the plus signs in front of a and b might look weird, but its a quick way to coerce a string into a number in javascript
You can strip out non-numeric characters, parse each number, and then perform the addition within the loop.
// variables
var sum = 0;
var average = 0;
var numOfSpan = $('span').length;
// each span loop
$('span').each(function(key, val){
// add the value of the span to the sum var
sum+= parseInt($(this).text().replace(/\D/g,''));
// on the last itteration ...
if(key == (numOfSpan - 1)) {
// calulate average
average = sum / numOfSpan;
// log sum and average
console.log('sum = ' + sum);
console.log('average = ' + average);
}
});
<span>(10)</span>
‎<span>(38)</span>
<span>(13)</span>
<span>(35)</span>
‎<span>(46)</span>
‎‎<span>(17)</span>
<span>(27)</span>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You have to iterate your array and then change every string to number. After that you can add every elements to itself.
var a = 0;
for(var i=0;i<newString.length;i++) {
a += parseInt(newString[i]);}
And then a will be the sum

Accessing indexes of a string inside an array and taking the sum

Ok so I am trying to access each individual number in the strings inside of this array.
var array = ['818-625-9945','999-992-1313','888-222-2222','999-123-1245'];
var str = "";
for (i=0; i<array.length; i++) {
str = array[i];
}
The problem is that this is the output: '999-992-1313'
and not the first element array[0]: '818-625-9945'
When I try doing a nested for loop to go through each element inside the string I am having trouble stating those elements.
var array = ['818-625-9945','999-992-1313','888-222-2222','999-123-1245'];
for (i=0; i<array.length; i++) {
for (j=0; j<array[i].length; j++) {
console.log(array[i][j]);
}
}
I do not know how to access each individual number inside of the string array[i]. I would like to find a way to make a counter such that if I encounter the number '8' I add 8 to the total score, so I can take the sum of each individual string element and see which number has the highest sum.
var array = ['818-625-9945','999-992-1313','888-222-2222','999-123-1245'];
for (i=0; i<array.length; i++) {
for (j=0; j<array[i].length; j++) {
if (array[i](j).indexOf('8') !== -1) {
// add one to total score
// then find a way to increase the index to the next index (might need help here also please)
}
}
}
Mabe this works for you. It utilized Array.prototype.reduce(), Array.prototype.map() and String.prototype.split().
This proposal literates through the given array and splits every string and then filter the gotten array with a check for '8'. The returned array is taken as count and added to the return value from the former iteration of reduce - and returned.
var array = ['818-625-9945', '999-992-1313', '888-222-2222', '999-123-1245'],
score = array.reduce(function (r, a) {
return r + a.split('').filter(function (b) { return b === '8'; }).length;
}, 0);
document.write('Score: ' + score);
A suggested approach with counting all '8' on every string:
var array = ['818-625-9945', '999-992-1313', '888-222-2222', '999-123-1245'],
score = array.map(function (a) {
return a.split('').filter(function (b) { return b === '8'; }).length;
});
document.write('Score: ' + score);
Actually rereading your question gave me a better idea of what you want. You simply want to count and retrieve the number of 8's per string and which index in your array conforms with this maximum 8 value. This function retrieves the index where the value was found in the array, how many times 8 was found and what is the string value for this result. (or returns an empty object in case you give in an empty array)
This you could easily do with:
'use strict';
var array = ['818-625-9945', '999-992-1313', '888-222-2222', '999-123-1245'];
function getHighestEightCountFromArray(arr) {
var max = 0,
result = {};
if (arr && arr.forEach) {
arr.forEach(function(value, idx) {
var cnt = value.split('8').length;
if (max < cnt) {
// found more nr 8 in this section (nl: cnt - 1)
max = cnt;
// store the value that gave this max
result = {
count: cnt - 1,
value: value,
index: idx
};
}
});
}
return result;
}
console.log(getHighestEightCountFromArray(array));
The only thing here is that when an equal amount of counts is found, it will still use the first one found, here you could decide which "maximum"
should be preferred(first one in the array, or the newest / latest one in the array)
OLD
I'm not sure which sums you are missing, but you could do it in the following way.
There I first loop over all the items in the array, then I use the String.prototype.split function to split the single array items into an array which would then contain ['818', '625', '9945']. Then for each value you can repeat the same style, nl: Split the value you are receiving and then loop over all single values. Those then get convert to a number by using Number.parseInt an then all the values are counted together.
There are definitelly shorter ways, but this is a way how you could do it
'use strict';
var array = ['818-625-9945','999-992-1313','888-222-2222','999-123-1245'],
sumPerIndex = [],
totalSum = 0;
array.forEach(function(item, idx) {
var values = item.split('-'), subArray = [], itemSum = 0;
values.forEach(function(value) {
var singleItems = value.split(''),
charSum = 0;
singleItems.forEach(function(char) {
charSum += parseInt(char);
});
itemSum += charSum;
subArray.push(charSum);
console.log('Sum for chars of ' + value + ' = ' + charSum);
});
sumPerIndex.push(subArray);
totalSum += itemSum;
console.log('Sum for single values of ' + item + ' = ' + itemSum);
});
console.log('Total sum of all elements: ' + totalSum);
console.log('All invidual sums', sumPerIndex);

Array text to numbers, find matching values and sort

I have an array which looks like this:
["1,8", "4,6,8", "8,9", "6,9"]
1/ I would like to turn it in to this
[1,8,4,6,8,8,9,6,9]
2/ I would then like to find matching values, by looking for the most number:
[8]
This first has been solved with this:
var carArray = ["1,8", "4,6,8,7,7,7,7", "8,9", "6,9"];
//1) create single array
var arr = carArray.join().split(',');
//2) find most occurring
var counts = {}; //object to hold count for each occurence
var max = 0, maxOccurring;
arr.forEach(function(el){
var cnt = (counts[el] || 0); //previous count
counts[el] = ++cnt;
if(cnt > max && cnt > 1){ //only register if more than once (cnt>1)
max=cnt;
maxOccurring = el;
}
});
if(maxOccurring){
//there was an element more than once, maxOccuring contains that element
setResult('Most occuring: ' + maxOccurring + ' (' + max + ' times)');
}
else{
//3)/4) ???
setResult('sorting?');
}
//below is only for test display purposes
function setResult(res){
console.log(res);
}
3/ If the are no matching values like this
[1,8,4,6,5,7]
4/ Then I need to compare this array to another array, such as this
[6,7,4,1,2,8,9,5]
If the first number in <4> array above appears in <3> array, then get that number, ie in the above example I need to get 6. The <4> array will be static values and not change. The numbers is <3> will be dynamic.
EDIT Not the most elegant of answers, but I do have something working now. I didn't compare the original array directly with the second array, instead used simple if/else statements to do what I needed:
var carArray = ["1,5", "4", "8,2", "3,9,1,1,1"];
//1) create single array
var arr = carArray.join().split(',');
//2) find most occurring
var counts = {}; //object to hold count for each occurence
var max = 0, maxOccurring;
arr.forEach(function(el){
var cnt = (counts[el] || 0); //previous count
counts[el] = ++cnt;
if(cnt > max && cnt > 1){ //only register if more than once (cnt>1)
max=cnt;
maxOccurring = el;
}
});
if(maxOccurring){
//there was an element more than once, maxOccuring contains that element
console.log('Most occuring: ' + maxOccurring + ' (' + max + ' times)');
console.log(maxOccurring);
}
else {
// If not occuring, match from a list
if(jQuery.inArray("6", arr) !== -1) { console.log('6'); }
else if(jQuery.inArray("9", arr) !== -1) { console.log('9'); }
else if(jQuery.inArray("7", arr) !== -1) { console.log('7'); }
else if(jQuery.inArray("5", arr) !== -1) { console.log('5'); }
else if(jQuery.inArray("4", arr) !== -1) { console.log('4'); }
else if(jQuery.inArray("1", arr) !== -1) { console.log('1'); }
else { console.log('not found'); }
}
Example Fiddle
Step 1 is fairly easy by using javascript's join and split methods respectively:
var arr = carArray .join().split(',');
For step 2, several methods can be used, the most common one using an object and using the elements themselves as properties. Since you only need to get the most occurring value if there is a reoccurring value, it can be used in the same loop:
var counts = {}; //object to hold count for each occurence
var max = 0, maxOccurring;
arr.forEach(function(el){
var cnt = (counts[el] || 0); //previous count
counts[el] = ++cnt;
if(cnt > max && cnt > 1){ //only register if more than once (cnt>1)
max=cnt;
maxOccurring = el;
}
});
After the above, the variable maxOccurring will contain the reoccurring value (if any) and max will contain the times it occured
For step 4 the easiest way is to loop through the compare array and get the element that occurs in the input array:
var cmpArr = ['6','7','4','1','2','8','9','5'];
//find the first occurrence inside the cmpArr
res = function(){ for(var i= 0 ; i < cmpArr.length; i++){ if(arr.indexOf(cmpArr[i]) !== -1)return cmpArr[i];}}();
The above uses an in place function which is called immediately to be able to use return. You could also just use a loop and assign res when found, then break from the loop.
Last update, an alternate fiddle where the above is converted to a single function: http://jsfiddle.net/v9hhsdny/5/
Well first of all the following code results in four matching answers since the jQuery selectors are the same.
var questionAnswer1 = $(this).find('input[name=questionText]').val();
var questionAnswer2 = $(this).find('input[name=questionText]').val();
var questionAnswer3 = $(this).find('input[name=questionText]').val();
var questionAnswer4 = $(this).find('input[name=questionText]').val();
var carArray = [questionAnswer1, questionAnswer2, questionAnswer3, questionAnswer4];
You could use the eq(index) method of jQuery to select the appropriate element. However having 4 inputs with the same name is a bad practice.
Well lets say that the carArray has 4 different values which all consist out of comma separated numbers. You could then do the following:
var newArr = [];
carArray.forEach(function(e) {
e.split(",").forEach(function(n) {
newArr.push(n);
});
});
Well then we got to find the most occurring number. JavaScript doesn't have any functions for that so we will have to find an algorithm for that. I found the following algorithm on this stackoverflow page
var count = function(ary, classifier) {
return ary.reduce(function(counter, item) {
var p = (classifier || String)(item);
counter[p] = counter.hasOwnProperty(p) ? counter[p] + 1 : 1;
return counter;
}, {})
}
var occurances = count(newArr);
It isn't clear to me what you're trying to do in step 3 and 4, so can't answer those at the moment.
var ary = ["1,8", "4,6,8", "8,9", "6,9"];
var splitted = ary.reduce(function(acc, item) {
return acc.concat(item.split(','));
}, []);
var occurences = splitted.reduce(function(acc, item) {
if (!acc.hasOwnProperty(item)) acc[item] = 0;
acc[item] += 1;
return acc;
},{}),
biggest = Object.keys(occurences).reduce(function (acc, key) {
if (occurences[key] > acc.occurences) {
acc.name = key;
acc.occurences = occurences[key];
}
return acc;
},{'name':'none','occurences':0}).name;
var vals=["1,8", "4,6,8", "8,9", "6,9"];
// 1) turn into number array
var arrNew=[];
for(var i=0; i<vals.length; i++)
{
arrLine=vals[i].split(",");
for (var j=0;j<arrLine.length;j++) { arrNew.push (parseInt(arrLine[j])) }
}
//result:
alert(arrNew.join(";");
// 2) find most common
var found=[];
for(var i=0; i<arrNew.length; i++) {
// make an array of the number of occurrances of each value
if (found["num"+newArray[i]]) {
found["num"+newArray[i]] ++ ;
} else {
found["num"+newArray[i]]=1;
}
}
var mostCommon={count:0,val:"ROGUE"};
for (x in found) {
if (found[x] > mostCommon.count) {
mostCommon.count=found[x].count;
mostCommon.val=x;
}
}
// result :
alert(mostCommon.val);
//3) not quite sure what you meant there
// 4) unique values:
// at this point the 'found' list contains unique vals
var arrUnique=[];
for (x in found) {
arrUnique.push[x];
}
// result :
alert(arrUnique.join(";"))
//sort:
arrUnique.sort(function(a, b){return a-b});
(This won't work in most browsers) but on a side note, when ES6 becomes widely supported, your solution could look like this:
var arr1 = ["1,8", "4,6,8", "8,9", "6,9"];
var arr2 = arr1.join().split(',');
var s = Array.from(new Set(arr2)); //Array populated by unique values, ["1", "8", "4", "6", "9"]
Thought you might like to see a glimpse of the future!
1.
var orgArray = ['1,8', '4,6,8', '8,9', '6,9'];
var newArray = [];
for (var i in orgArray) {
var tmpArray = orgArray[i].split(',');
for (var j in tmpArray) {
newArray.push(Number(tmpArray[j]));
}
}
2.
var counts = {};
var most = null;
for (var i in newArray) {
var num = newArray[i];
if (typeof counts[num] === 'undefined') {
counts[num] = 1;
} else {
++(counts[num]);
}
if (most == null || counts[num] > counts[most]) {
most = num;
} else if (most != null && counts[num] === counts[most]) {
most = null;
}
}
I don't understand the question 3 and 4 (what "unique order" means) so I can't answer those questions.

jQuery each in a each?

I will create a dynamic webshop product loader and have this i array output from my system.
{"product":[{"picture":".jpg","title":"test","category":"varenummer","price":"500,00 kr.","onStock":"1","status":"test"},{"picture":".jpeg","title":"test test","category":"varenummerssss","price":"550,00 kr.","onStock":"5","status":"test s"}]}
i don't know how i can create this each loop out.
var data = {"product":[{"picture":".jpg","title":"test","category":"varenummer","price":"500,00 kr.","onStock":"1","status":"test"},{"picture":".jpeg","title":"test test","category":"varenummerssss","price":"550,00 kr.","onStock":"5","status":"test s"}]}
$.each(data.product, function() {
$.each(this, function(key, value) {
// key = picture, title, etc
// value = .jpg, test, etc
});
});
in jQuery.each the second argument is set as this for the scope. So this === arguments[1]
jQuery is overkill to loop through a list.
Fairly straight forward and very simplified:
var list = {"product":[{"picture":".jpg","title":"test","category":"varenummer","price":"500,00 kr.","onStock":"1","status":"test"},{"picture":".jpeg","title":"test test","category":"varenummerssss","price":"550,00 kr.","onStock":"5","status":"test s"}]};
var i, len, product;
for(i = 0, len = list.product.length; i < len; i++)
{
product = list.product[i];
alert(product.picture + " and " + product.title);
}
Example

Categories