occurences of words in an array in JavaScript [duplicate] - javascript

This question already has answers here:
How to count the number of occurrences of each item in an array? [duplicate]
(9 answers)
Closed 9 years ago.
I have an array my
array=["hello","goodbye","hello","hello","goodbye"];
and i want this array to count the occurrences of each word and print a table with each word and how many times is seen to the array in JavaScript. Can you help me please?

Try this:
var array=["hello","goodbye","hello","hello","goodbye"];
var count = {};
for (var i = 0; i < array.length; i++) {
count[array[i]] = (count[array[i]] || 0) + 1;
}
console.log(count);
HTML Output:
var table = document.createElement('table');
for (var word in count) {
var tr = document.createElement('tr');
tr.innerHTML = '<td>' + word + '</td><td>' + count[word] + '</td>';
table.appendChild(tr);
}
document.body.appendChild(table);

Related

How to find mean of an array using Javascript [duplicate]

This question already has answers here:
How to compute the sum and average of elements in an array? [duplicate]
(35 answers)
Closed 10 months ago.
I tried to iterate through the array and print the sum. But the output am getting is elements of the array.
<p id="ans"></p>
<script>
var text = "the mean is ";
function mean() {
var sum = 0;
var input = document.getElementsByName("values");
for (var i = 0; i < input.length; i++) {
sum += input[i].value;
text = text + sum;
}
document.getElementById("ans").innerHTML = text;
}
</script>
Parse the string values into integers and then sum it.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt
This is because in javascript if you adding a number to a string it will be casted to a string. For example:
0 + '1' + '2' // 012
But with parse int:
0 + parseInt('1') + parseInt('2') // 3
Or you can cast to int with a simple plus also:
0 + (+'1') + (+'2') // 3

Javascript: iterate through array and add % after each element except last [duplicate]

This question already has answers here:
How to convert array into comma separated string in javascript [duplicate]
(3 answers)
Closed 2 years ago.
I want to add a % after each element in the array except the last. So far I have come up with this:
var array = [a, b, c];
for(var i=0; i<array.length; i++) {
var outcome += array[i] + '%';
}
Outcome:
a%b%c%
How can I fix this so the % does not appear at the end of the outcome?
You can use the Array.prototype.join method in order to get what you're after:
console.info(['a', 'b', 'c'].join('%'))
Check if the current element (value of i) is not the last element. If it's the last element don't concatenate a %, for all others concatenate with the %.
for(var i = 0; i < arr.length; i++) {
if(arr[i] < arr.length -1) {
var outcome += arr[i] + '%';
}
}

Compare arrays with JS and print result in matrix table

I am trying to make a matrix table by combining values from array. First array holds information about user for specific day. Second array holds list of users, third array holds days in month.
First I get data from api.
var odgovor = JSON.parse(http.responseText);
dataSetMoj = odgovor.urvPoDanuZaMjesec;
dataSetMojUposlenik = odgovor.uposlenici;
Get days for month
var mjesecImaDana = getDaysInMonth(1,2018);
var daniMjeseca = [];
for (i = 1; i <= mjesecImaDana; i++) {
daniMjeseca.push([i]);
}
Then I create table header
var k = '<thead>';
k +='<tr><th style="background-color: #f8f7f7" >' + rb + '</th>';
k +='<th style="background-color: #f8f7f7" >' + up + '</th>';
daniMjeseca.forEach(function(daysInmonth){
k += '<th style="background-color: #f8f7f7"> '+ daysInmonth +'</th>';
});
k += '</tr></thead>';
Table header display correct information, as could be seen in img.
Array rezultati holds information about each user on specific day
var rezultati = [];
for(i = 0;i < dataSetMoj.length; i++){
rezultati.push(dataSetMoj[i].ime+'-'+dataSetMoj[i].datum+'-'+dataSetMoj[i].urv);
}
Then I create table body, In table body I should match user with date.
k += '<tbody>'
for(i = 0;i < dataSetMojUposlenik.length; i++){
k+='<tr>';
k+='<td> ' + a++ + '</td>';
k+='<td> ' + dataSetMojUposlenik[i].ime + '</td>';
daniMjeseca.forEach(function(daysInmonth){
var dataSetVar = dataSetMojUposlenik[i].ime +'-'+daysInmonth;
//here I should check if variable 'datSetVar' is set in array rezultati, if yes I should print dataSetMoj[i].urv from rezultati
if(rezultati == dataSetVar ){
k+='<td> ' + dataSetMoj[i].urv + '</td>'; // It does not work, but I have no idea. I could not find solution any hint would help me.
}
else{
k+='<td> ' + c + '</td>';
}
});
k+='</tr>';
}
k+='</tbody>';
document.getElementById('tableData').innerHTML = k;
Array rezultati holds three element dataSetVar two. I am not able to make comparison got wrong answers.

Using the same variable in 2 functions in javascript [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 5 years ago.
Here is what we're trying to do:
$(document).ready(function()
{
for (var i = 0; i < 10; i++)
{
for (var j = 0; j < 15; j++)
{
$('#Row'+(i+1)+'Sub' + (j+1) + '_ClientDropDown').ready(function()
{ TrimServices_Function( "Row" + (i+1) + "_Sub" + (j+1).ToString() + "_ClientDropDown"); })
}
}
})
Unfortunately, Javascript doesn't really pass the i and j into the second function correctly. When doing alerts in other tests it creates a line with the right initial call, but then the other part just returns 10 and 15. So lets say line 5 sub 7 would be:
$('#Row5Sub7_ClientDropDown').ready(function()
{ TrimServices_Function( "Row11_Sub16_ClientDropDown"); })
How would we go about making sure that we loop through lines where the row and sub match up?
Set both strings outside of the function inside the second for loop like this (I would also clean up your string concatenation, but I left it as you had it here):
for (var i = 0; i < 10; i++)
{
for (var j = 0; j < 15; j++)
{
var selectorA = '#Row'+(i+1)+'Sub' + (j+1) + '_ClientDropDown';
var selectorB = "Row" + (i+1) + "_Sub" + (j+1).ToString() + "_ClientDropDown";
$(selectorA).ready(function()
{ TrimServices_Function(selectorB); })
}
}

Jquery:for loop or $.each [duplicate]

This question already has answers here:
$().each vs $.each vs for loop in jQuery?
(3 answers)
Closed 8 years ago.
i have a doubt about the following scripts which one produce a better performance and how?
Using For Loop:
var words=$(".countryList option:selected").text().split(/ +/);
var sum=0;
var limit=14;
var appendWord="";
for(var i = 0; i < words.length; i++){
sum = sum + words[i].length;
if(sum <= limit){
appendWord = appendWord + " " + words[i];
sum = sum + 1;
}
}
Using $.each() :
var words =$(".countryList option:selected").text();
var arr = words.split(/ +/);
var textLimit=13;
var length=0;
var splittedText= '';
$.each(arr,function(i, val){
length = length + arr[i].length;
if(length <= textLimit){
splittedText = splittedText + ' ' + arr[i];
length = length + 1;
}
});
Here i get the Text from select box and tell to select box to display limited words or characters only..
Yes if we are taking about perfoemance: for loop is much faster than each .
You can verify the same using the console with date funciton that will show the curent date.

Categories

Resources