How to count a javascript array and get output like this? - javascript

i have a array like this
["5763.34", "5500.00", "5541.67", "5541.67"]
i want to count similar values and get a out put like
(1 * 5763.34) + (1 * 5500.00) + (2 * 5541.67)
any idea how to do this?

Count values:
var array = ["5763.34", "5500.00", "5541.67", "5541.67"]
var counts = {};
for (var i = 0; i < array.length; ++i) {
var val = array[i];
if (val in counts) {
counts[val]++;
} else {
counts[val] = 1;
}
}
Print them:
var strings = [];
for (var k in counts) {
strings.push('(' + counts[k] + ' * ' + k + ')');
}
alert(strings.join(' + '));
Try it here: http://jsfiddle.net/k46kL/1

do it like this
sum = 0
for(i=0; i< array.length; i++){
sum += array[i] * (i+1)
}

Related

Adding asterisks to array?

I'm trying to add elements as asterisks inside array based on number of elements. Basically If numberOfRows is 3 then I want this output:
[
' * ',
' *** ',
'*****'
]
I'm struggling on setting asterisks using the index. Can anyone point me in the right direction? Thanks a lot!
Here's my code:
function myFunction(numberOfRows) {
var arr = [];
var value = "";
var asterisk = "*"; // Need to update this based on number of rows
for (var i = 1; i <= numberOfRows; i++) {
value += asterisk;
arr.push(value);
}
return arr;
}
Got it working! Here's a perfect solution.
function myFunction(n) {
let arr = [];
for(let f = 1; f <= n; f++) {
arr.push(' '.repeat(n - f) + '*'.repeat(f + f - 1) + ' '.repeat(n - f));
}
return arr;
}
console.log(myFunction(3));
Try something like this;
function myFunction(numberOfRows) {
var arr = [];
var value = "";
var slots = numberOfRows * 2 - 1;
var spaceSlots, asteriskSlots, spaces;
for (var i = 0; i < numberOfRows; i++) {
asteriskSlots = i * 2 + 1;
spaceSlots = Math.floor((slots - asteriskSlots)/2);
spaces = new Array(spaceSlots).fill(' ').join('');
value = spaces + '*'.repeat(asteriskSlots) + spaces;
arr.push(value);
}
return arr;
}
console.log(myFunction(20));

Array loop in javascript

I try to develop a simple program that prints all numbers in between 1 and 100 that divide by 3 without any residual and calculate the total sum
I did it with for loop:
var sum = 0;
for (var i = 3; i <= 100; i = i + 3) {
document.write("<br/>" + i);
sum = sum + i;
}
document.write("<br/>sum = " + sum); //1683
But I failed when I wanted to do it with array:
var numbers = [];
var sum = 0;
for (var i = 0; i <= 100; i = i + 3) {
numbers[i - 1] = i;
}
for (var index = 0; index < 100; index++) {
document.write("<br/>" + numbers[index]);
sum = sum + i;
}
document.write("<br/>sum = " + sum);
Use it like this,
Array indexes should start from 0, that is why I have introduced another variable j=0
var numbers = [];
var sum = 0;
for (var i = 0, j = 0; i <= 100; i = i + 3, ++j) {
numbers[j] = i;
}
Update
First Issue:
In your code, ie. below code of yours,
for (var i = 0; i <= 100; i = i + 3) {
numbers[i - 1] = i;
}
In the first iteration,
i = 0;
numbers[0-1] = i // i.e numbers[-1] = 0;
and in your second loop, you are starting the index from 0
for (var index = 0; index < 100; index++) {
Second issue:
Also, if you don't use a sequential counter to fill the Array, you will end with undefined values for the ones you did not fill.
If you notice, the output after the loop, it says numbers.length = 99 which is wrong it will not have that many items in it.
Third Issue:
In below code, even if you introduce a sequential counter, this is still wrong
for (var i = 0; i <= 100; i = i + 3) {
numbers[i - 1] = i;
}
because i should start with 3 instead of 0, otherwise you will end up with 34 elements in the array because numbers[0] will be 0;
Fourth Issue:
In this code,
for (var index = 0; index < 100; index++) {
document.write("<br/>" + numbers[index]);
sum = sum + i;
}
You don't actually have to loop it till 100, you already have the numbers array filled, so you just need to use numbers.length, like this
var len = numbers.length;
for (var index = 0; index < len; index++) {
document.write("<br/>" + numbers[index]);
sum = sum + i;
}
A better way to write this
var numbers = [];
for (var i = 3, j=0; i <= 100; i = i + 3, j++) {
numbers[j] = i;
}
var sum = numbers.reduce((a, b) => a+b);
console.log(sum);
The line var sum = numbers.reduce((a, b) => a+b); uses Array.reduce() method.
adding number to array
var numbers = [];
for(var i = 3; i <= 100; i = i +3){
numbers.push(i);
}
summation and printing values
var sum = 0;
for (var i = 0; i < numbers.length; i++) {
document.write("<br/>" + numbers[i]);
sum = sum + numbers[i];
}
document.write("<br/>sum = " + sum); //1683
There are few issues in your code.
for (var i = 0; i <= 100; i = i + 3) {
numbers[i - 1] = i;
}
1: array is 0 based. so first insertion into the array goes for a toss.
2: the number array created will have skipping index like 3, 6 ,9
for (var index = 0; index < 100; index++) {
document.write("<br/>" + numbers[index]);
sum = sum + i;
}
3: Here you are iterating index till 100 , you should iterate it till the length of the numbers array only.
when index is 1,2
number[index] will become undefined.
4: sum = sum + i (i ??????)
You should try like this or you can also use push()
var numbers = [];
var sum = 0;
for (var i = 0,j=0; i <= 100; i = i + 3, j= j+1) {
numbers[j] = i; // array is 0 based.
}
for (var index = 0; index < numbers.length; index++) {
document.write("<br/>" + numbers[index]);
sum = sum + numbers[index];
}
document.write("<br/>sum = " + sum);
Indexes in an array begin with zero.
for (var i = 0; i <= 100; i = i + 3) {
numbers[i - 1] = i; // In the first iteration, there will be numbers[-1] = i;
}
You have several issues i suppose.
var numbers = [];
var sum = 0;
for (var i = 0; i <= 100; i = i + 3) {
numbers.push(i);
}
for (var index = 0; index < numbers.length; index++) {
document.write("<br/>" + numbers[index]);
sum = sum + i;
}
document.write("<br/>sum = " + sum);
Also for array you can use:
for (var i in array) {
console.log(array[i]);
}
And I'm pretty sure, that array of number sequence is absolutely useless, if there is no other information in it.
Try this
var numbers = [];
var sum = 0;
for (var i = 0; i <= 100; i = i + 3) {
numbers[(i-3)/3] = i;
}
for (var index = 0; index < numbers.length; index++) {
document.write("<br/>" + numbers[index]);
sum = sum + numbers[index];
}
document.write("<br/>sum = " + sum);
Here is the fiddle i tried
https://jsfiddle.net/4ncgnd7c/
This should work using a single loop
var numbers = [];
var sum = 0;
for (var i = 3; i <= 100; i = i + 3) {
numbers[i] = i;
document.write("<br/>" + i);
sum = sum + i;
}
document.write("<br/>sum = " + sum);

How to console.log multiplication table without repeating x*y=z, y*x=z

How to make multiplication table without repeating reverse calculations like this xy=z yx=z? I tried to use if else with !== operator but it shows nothing. My code:
for (var x = 1; x <= 10; x++) {
for (var i = 1; i <= 10; i++) {
var result = x * i;
if (result !== result){
console.log(x + ' * ' + i + ' = ' + result);
}
else {
}
}
}
Pretty simple :
for (var x = 1; x <= 10; x++) {
for (var i = x; i <= 10; i++) {
var result = x * i;
console.log(x + ' * ' + i + ' = ' + result);
}
}
Replace i = 1 by i = x on the second line so that it starts later and ignores all the previous calculations it already did.
E.G.: When you're calculating the table 3, you can start with 3*3 as you already already did 3*1 (1*3) with table 1 and 3*2 (2*3) with table 2
You could keep track of the calculations you've already done in an hash table. If it's already in the table - skip that calculation. Something like this:
var doneCalculations = {};
for (var x = 1; x <= 10; x++) {
for (var i = 1; i <= 10; i++) {;
if (doneCalculations[i+'x'+x]) continue;
doneCalculations[x+'x'+i] = true;
var result = x * i;
console.log(x + ' * ' + i + ' = ' + result);
}
}
start the second loop with first loop variable
for (var x = 1; x <= 10; x++) {
for (var i = x; i <= 10; i++) {
var result = x * i;
console.log(x + ' * ' + i + ' = ' + result);
}
}
You want to print full multiplication table for each values of x, 1 to 10. Use memoization to avoid recalculation
In computing, memoization or memoisation is an optimization technique used primarily to speed up computer programs by storing the results of expensive function calls and returning the cached result when the same inputs occur again.
var doneCalculations = {};
var calculations = {};
var doneCalculations = {};
for (var x = 1; x <= 10; x++) {
for (var i = 1; i <= 10; i++) {;
if (doneCalculations[i+'x'+x]) {
result = calculations[i+'x'+x]
}
else {
doneCalculations[x+'x'+i] = true;
var result = x * i;
calculations[x+'x'+i] = result;
}
console.log(x + ' * ' + i + ' = ' + result);
}
}
console.log(calculations)

Javascript: Keep count of even and odd random numbers and get the sum of each

When I run this program I am only getting the even number count and the odd sum. The odd count and even sum just gives me 0 every time.
Does anyone have any idea what I am missing? Thanks!
I am trying to generate 100 random numbers and keep count of the evens/odds and then get the sum of each.
var min = 1;
var max = 1000;
var randomNumArray = []
var oddCount = []
var evenCount = []
var oddSum = []
var evenSum = []
function isEven(x){
if (x % 2 == 0)
return true;
else
return false;
}
function sumOfArray(evenSum){
for(i = 0; i< evenSum.length; i++){
if (isEven){
return(evenSum);
}
else{
return (oddSum);
}
}
}
for( i = 0; i < 100; i++){
var randNumber = Math.floor(min + (Math.random() * max));
randomNumArray.push(randNumber);
}
for( i = 0; i< randNumber.length; i++){
if (isEven(evenCount[i])){
return evenCount;
}
else{
return oddCount;
}
}
console.log('Even Number Count: ' + evenCount);
console.log('Odd Number Count: ' + oddCount);
console.log('Sum Even: ' + evenSum);
console.log('Sum Odd: ' + oddSum);
I would just use 1 function to check if its even or odd and then decide to add the sum by the number itself and the count by 1. You are making it way more complicated and I'm wondering why u are using arrays.
Try something like this:
for( i = 0; i < 100; i++){
var randNumber = Math.floor(min + (Math.random() * max));
if(isEven(randNum)){
evenSum = evensum+randNum;
evenCount ++;
}else{
oddSum= oddSum+randNum;
oddSum++;
}
}
var oddCount = 0
var evenCount = 0
for(i=0; i<randomNumArray.length; i++) {
if(randomNumArray[i] % 2 == 0) {
evenCount++
} else {
oddCount++
}
};
Something like that should work?

Convert array to string while grouping by pairs

I have an array of latitudes and longitudes in javascript, like this:
a = [lat1, lon1, lat2, lon2, lat3, lon3, ...] // assert(a.length % 2 = 0)
and I would like to create a string like this:
s = "lat1,lon1 lat2,lon2 lat3,lon3 ..."
that is, each latlon pair has a comma separating the pair, and the pairs are separated by a space.
I'm a bit stuck here (mostly because I know very little of javascript):
function polylineToKml(p)
{
var s = "";
for (var i = 0; i < p.length; i+=2)
{
var lat = p[i];
var lon = p[i+1]
// now what?
}
}
In a more functional way:
function polylineToKml(p) {
return p.map(function(el, i) {
return el + (i % 2 > 0 ? " " : ",");
}).join("").trim();
}
And if your environment supports ES6:
var polylineToKml = p =>
p.map((el, i) => el + (i % 2 > 0 ? " " : ",")).join("").trim();
One way:
var s = [];
for (var i = 0; i < a.length; i+=2)
{
s.push(a[i] + "," + a[i+1]);
}
s = s.join(" ");
function polylineToKml(p) {
var s = "";
for (var i = 0, l = p.length; i < l; i += 2) {
var lat = p[i];
var lon = p[i + 1];
s += lat + ',' + lon;
// don't add a space at the end
if (i !== l - 2) s += ' ';
}
return s;
}
DEMO
one more way...
function polylineToKml(p){
var s = "";
for (var i = 0; i < p.length - 1; i++){
s += p[i] + ",";
}
s += p[p.length - 1];
return s;
}
You should adopt a proper way to organize your data set, one way is to use JSON array with key-value pairs, e.g.
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var a = [1.234, 2.345, 3.456, 5.456, 4.653, 2.567]
var coordinates = [];
for (var i=0; i < a.length; i=i+2){
coordinates[i/2] = {"latitude":a[i], "longitude":a[i+1]}
}
for (var i=0; i < coordinates.length; i++){
document.getElementById("demo").innerHTML +=
coordinates[i].latitude + ", " + coordinates[i].longitude + "<br>";
}
</script>
</body>
</html>
In this way, the coordinates will be represented as such:
coordinates = [
{"latitude":"1.234", "longitude":"2.345"},
{"latitude":"3.456", "longitude":"5.456"},
{"latitude":"4.653", "longitude":"2.567"}
];
Find out more on http://www.w3schools.com/json/default.asp

Categories