Match a range of rows in an array? jQuery, Javascript - javascript

I'm unsure how else to write the title but it's about as close as I can get to what I'm after.
I have a calculator I'm trying to create that compares values in a number of arrays.
Each data object in my array has 34 rows, some of which have the same number/value in them.
At the minute if you select france, I only want 1 of each grade to show in the dropdown, so the number 1 would appear once.
If you select France and grade 1, I want the outputted value to say the lowest value in that range to the highest, in this case USA would output 3 to 5 does this make sense?
If so I'm wondering how I'd possibly do this?
JSFiddle
http://jsfiddle.net/R85Qj/

Does this help?
http://jsfiddle.net/R85Qj/2/
$("#convert").on("click", function () {
var gradeIndex = $("#grade").val();
var gradeConversion = "";
/* gradeConversion += "<span>" + countryGrades[countryGradesIndex].country + ": " + countryGrades[countryGradesIndex].grades[gradeIndex][1] + "</span>";*/
var indexes = [];
var countryIndex = $("#country").val();
var gradeValue = countryGrades[countryIndex].grades[gradeIndex][0];
// find all indexes of gradeValue
for(var i = 0; i < countryGrades[countryIndex].grades.length; i++) {
if (countryGrades[countryIndex].grades[i][1] == gradeValue) {
indexes.push(i);
}
}
allValues = [];
for(var c = 0; c < countryGrades.length; c++) {
gradeConversion += countryGrades[c].country + ":";
for(i = 0; i < indexes.length; i++) {
if (i == 0 || countryGrades[c].grades[indexes[i]][1] != countryGrades[c].grades[indexes[i-1]][1]) {
gradeConversion += countryGrades[c].grades[indexes[i]][1] + " ";
}
}
}
$("#conversions").html(gradeConversion);
});

Related

Javascript Fib series test case fails

I am trying to complete this assignment for the Javascript Fibonacci series. The logic works for input 5 and 6. But the test case for 8 fails.
function fibonacciSequence(input) {
//Type your code here.
var i = 0;
var fib = [];
fib[0] = 0;
fib[1] = 1;
var out ="0"+ "" +"1";
for (i = 2; i <=input; i++) {
fib[i] = fib[i-2] + fib[i-1];
out = out+ ""+ fib[i];
console.log("i is" + i + " out is" + out);
}
return out;
}
I cannot figure out what is going wrong..
It seems like things are just getting messed up with how you are adding the items to the string. Since there is no space between out + "" + fib[i], I think that would be messing with the formatting. Once i had spaces it seems to work fine, a double digit number wouldnt mess with a string like that.
function fibonacciSequence(input) {
var fib = [];
fib[0] = 0;
fib[1] = 1;
let out = ""
out+= ` ${0} `
out+= `${1}`
for (let i=2; i <=input; i++) {
fib[i] = fib[i-2] + fib[i-1];
out+= ` ${fib[i]}`
}
return out;
}
You are comparing the input (which it seems like this is maybe the number you want to stop at) to i which (plus or minus a bit) is the number of numbers in the list. You probably want to be comparing fib[i], or something like it to input to decide whether to terminate the loop.
Edit: If that's wrong and you do want input to be the number of numbers in the list, then you could just join fib at the end:
function fibonacciSequence(input) {
//Type your code here.
var i = 0;
var fib = [];
fib[0] = 0;
fib[1] = 1;
//var out ="0"+ "" +"1";
for (i = 2; i <=input; i++) {
fib[i] = fib[i-2] + fib[i-1];
//out = out+ ""+ fib[i];
//console.log("i is" + i + " out is" + out);
}
return fib.join(' ');
}
for(let j = 0; j < 9; j++)
console.log('input: ' + j + ' :: ', fibonacciSequence(j));
Unless ... I've got the wrong end of the stick and #Grant Herman's answer already does what you want?

Need to make a list of the outstanding GPA’s from the array Im making (GPA’s over 3.4). Prefer traditional loop solution over some ES6 function

I need help with getting a list of GPAs over 3.4. I was able to sort largest to smallest, average, and get min and max GPAs utilizing traditional approaches (not ES6).
<div id ="out"></div>
<script>
var gpas = [];
var thegpas = " ";
var total = 0
while (thegpas != "XXX")
{
thegpas = prompt("Enter gpas or XXX to Stop");
if(thegpas != "XXX"){
gpas.push(thegpas);
} else {
break;
}
}
for(var x = 0; x < gpas.length; x++)
{
a = gpas.sort((a,b)=>b-a);
total=total + parseFloat(gpas[x]);
b = total/gpas.length //parseFloat(total)/length;
var max = gpas[0];
var min = gpas[0];
for(var i = 1; i < gpas.length; ++i) {
if (gpas[i]>max) {
max = parseFloat(gpas[i]);
}
else if (gpas[i] < min) {
min = parseFloat(gpas[i]);
}
}
//need help with this part
//outstandingGPAs=0;
outstandingGPAs = [];
cutoff = 3.4;
if (gpas[x]>cutoff){
outstandingGPAs.push(parseFloat(gpas[x]));
}
out= "Largest to smallest " + a + "<br/>" + "GPAs average: " + b + "<br/>" + " Max and Min: " + max + ", " + min + "<br/>" + "Outstanding GPAs (greather than 3.4): " + outstandingGPAs ;
// alert(gpas[x]);
}
document.getElementById('out').innerHTML=out;
Current Output:
Best way to output a (not very long) array is the join function.
In your output, you should use:
out = "<whatever you put>" + outstandingGPAs.join();
Check this link for more explanation of the join function.
Since you are already looping over your gpas array you could save those that are over 3.4 while you do that.
You would do that within your existing loop, not afterwards.
const cutoff = 3.4;
let outstandingGPAs = [];
// ...
for (var i = 1; i < gpas.length; ++i) {
if (gpas[i]>max) {
max = parseFloat(gpas[i]);
}
else if (gpas[i] < min) {
min = parseFloat(gpas[i]);
}
// added to the existing loop
if (gpas[i] > cutoff) {
outstandingGPAs.push(gpas[i]);
}
}
The outer loop should not be there, as you just redo the same operation over and over again.
As you only push at most one value in outstandingGPAs after you have set it to the empty array, that result will be wrong.
There are several other similar issues going on...
Also, getting input with prompt is really not user-friendly. The way to do this, is using an input element, and let the user type all values freely, and go back and correct whenever they want, and when they are happy with it, they can press a button so the code can run on it.
Here is how that looks:
var calcButton = document.getElementById("calc");
var gpasInput = document.getElementById("gpas");
var outDiv = document.getElementById('out');
calcButton.addEventListener("click", function () {
var min = Infinity,
max = -Infinity,
total = 0,
gpas = [],
outstandingGPAs = [];
// Collect the input as an array of strings with number-related characters
var inputStrings = gpasInput.value.match(/-?\d+(\.\d+)?/g);
for (var i = 0; i < inputStrings.length; i++) {
var num = parseFloat(inputStrings[i]);
gpas.push(num);
if (num > 3.4) {
outstandingGPAs.push(num);
}
if (num < min) {
min = num;
}
if (num > max) {
max = num;
}
total += num;
}
var average = total / gpas.length;
gpas.sort((a, b) => b - a);
// lets also sort the outstanding GPAs
outstandingGPAs.sort((a, b) => b - a);
outDiv.innerHTML = "Largest to smallest " + gpas.join(", ") + "<br>"
+ "GPAs average: " + average + "<br>"
+ "Max and Min: " + max + ", " + min + "<br>"
+ "Outstanding GPAs (greather than 3.4): " + outstandingGPAs.join(", ");
});
Enter gpas values: <input id="gpas">
<button id="calc">Calculate</button><br>
<div id ="out"></div>
Here:
let theGpas = "";
let gpaArr = [];
while(theGpas != "XXX"){
theGpas = prompt("Enter GPAs. Enter XXX to stop.");
if(theGpas != "XXX"){
gpaArr.push(theGpas);
}
}
gpaArr = gpaArr.sort();
document.write("Largest to Smallest: "+gpaArr.join(",")+"<br/>");
function average(array){
var totalSum = 0;
for(var n in array){
totalSum += array[n];
}
return totalSum/array.length;
}
function moreThanArray(array, comparison){
var returnArr = [];
for(var z in array){
if(array[z]>comparison){
returnArr[returnArr.length] = array[z];
}
}
return returnArr;
}
const averageOf = average(gpaArr);
document.write("GPAs average: "+averageOf+"<br/>");
document.write("Max and Min: "+gpaArr[gpaArr.length-1]+", "+gpaArr[0]);
document.write("<br/>"+"Outstanding GPAs (greater than 3.4): "+moreThanArray(gpaArr, 3.4).join(","));

Why is not working when i try to add a to a string to my array location

I'm still learning JavaScript, and now I'm in the array chapter and I'm doing this project I have to ask the user for 5 names and stored and my array, then have to sort the names by the location in the array, so i could separed in odd and in even, then i have to add a lastname to the odds, and different last name to the even, but is that part that is not working any help ... THANKS
var numberfirstNames = 5;
var userMessage = " Please enter a first Name" ;
var secondArray = [];
var odd2 = [];
var even2 = [];
for (var i = 0; i < numberfirstNames; i++) // loop 5 times LOOL ASKING FOR "5" FIRST NAMES>> STORING IN NAMES
{
secondArray[i] = getFirstname();
window.alert("second " + secondArray[i] );
}
for (var i = 0; i < secondArray.length; i++) {
if(i % 2 === 0) // index is even
{
even2.push(secondArray[i]);
for ( var i=0 ; i<even2.length; i++)
even2[i]+=" Chavez"
}
else
{
odd2.push(secondArray[i]);
for ( var i=0 ; i<odd2.length; i++)
odd2[i]+=" McCain"
}
}
document.write(" \n all the names: "+ secondArray+'<br>');
document.write(" \n even names: "+ even2+'<br>');
document.write(" \n odd names: "+ odd2+'<br>');
The problem is that you are making a second loop that is unnecessary... the code
for ( var i=0 ; i<even2.length; i++)
and
for ( var i=0 ; i<odd2.length; i++)
should be simply removed.
You need to add first or last name only to last element added to odd2 or even2 and this can be done with:
even2[even2.length-1]+=" Chavez"
and
odd2[odd2.length-1]+=" McCain"
It is important to get used adding correct indentation because this kind of error is much easier to spot in the code when it is properly indented.
You don't need to loop again to add the specific last name. You can just prepend it while you are inserting it into the array like below.
var numberfirstNames = 5;
var userMessage = " Please enter a first Name";
var secondArray = [];
var odd2 = [];
var even2 = [];
// loop 5 times LOOP ASKING FOR "5" FIRST NAMES >> STORING IN NAMES
for (var i = 0; i < numberfirstNames; i++) {
secondArray[i] = getFirstname();
window.alert("second " + secondArray[i]);
if (i % 2 === 0) {
even2.push(secondArray[i] + " Chavez");
} else {
odd2.push(secondArray[i] + " McCain");
}
}
document.write(" \n all the names: " + secondArray.join(",") + '<br>');
document.write(" \n even names: " + even2.join(",") + '<br>');
document.write(" \n odd names: " + odd2.join(",") + '<br>');

JavaScript - Printing from Array of Objects Not Working

I have this array of objects here that I am traversing and want to display a match if the person at the current index has an age within +/- 10 years of anyone else in the array. However, when I run it, it says "Cannot read property 'age' of undefined." Where did I go wrong?
function findmatches() {
var n = USERS.length;
for (var i = 0; i < n; i++) {
var currName = USERS[i].firstName;
var currAge = USERS[i].age;
var currGender = USERS[i].gender;
for (var c = 0; c < 10; c++) {
if (((USERS[c].age) + 10) <= currAge) {
document.getElementById("showmatches").innerHTML += currName + " matched to >> " + USERS[i].firstName + " " + USERS[i].lastName + " \n";
break;
}
}
}
}
What exactly is your second for loop supposed to do?
In the code you posted, it iterates through first 10 users in the USERS array. I assume it has less users than that, so at some point USERS[c] is undefined, and you're trying to access USERS[c].age.

How to format the element inside an array?

I have three arrays for example:
var name = ["wheel", "rectangle", "moon"];
var type = ["car", "shape", "sky"];
var all = [];
var temp = " ";
for (var i = 0; i < name.length; i++) {
temp = name[i] + " " + type[i];
all.push(temp);
}
for (var i = 0; i < name.length; i++) {
// I call here function to display all element of array `all`
}
The output is:
wheel car
rectangle shape
moon sky
But the format of output is not nice. I want to shift the element of array type before add them to array all, so I want the output to be like:
wheel car
rectangle shape
moon sky
My question is: how can I shift elements of the array to add them to another array and store them in a way that allows to me to display the elements like form above ?
But the form of output not nice
If you simply want to format the output in a better way, then try console.table
var name1 = [ "wheel","rectangle","moon" ];
var type = [ "car" , "shape", "sky"];
var all=[];
for (var i = 0; i< name1.length; i++)
{
all.push({ name : name1[i], type: type[i] });
}
console.table(all);
Try this fiddle to see the actual output since stack-snippet alters the behaviour of console api
You should calculate which is the longest string in the first array so to know in advance how many spaces you need to append to correctly pad the string
var n = ["wheel", "rectangle", "moon"];
var t = ["car", "shape", "sky"];
var all = [];
/* sorting the values of the first array by length desc,
* then get the length of the first element
*/
var padding = n.sort(function(a, b) {
return a.length <= b.length;
})[0].length + 1;
n.forEach(function(el, i) {
all.push(el + " ".repeat(padding - el.length) + t[i]);
});
Output
"rectangle car"
"wheel shape"
"moon sky"
codepen demo
First loop over the array and find the max length. Then loop again and add spaces.
<script >
var name=["wheel","rectangle","moon"];
var type=["car","shape","sky"];
var all=[];
var i=0;
var maxLength=0;
string temp=" ";
String.prototype.padLeft= function(len, c){
var r = '';
while(r.length < len) r += c;
return s+r;
}
for (i = 0; i< name.length; i++)
{
maxLength = Math.max(maxLength, name[i].length+type[i].length+1;
}
for (i = 0; i< name.length; i++)
{
temp=name[i]+type[i].padLeft(maxLength-name[i].length-type[i].length);
all.push(temp);
}
</script >
I would do as follows;
var id = ["wheel","rectangle","moon"],
type = ["car","shape","sky"];
id.longestStringLength = Math.max(...id.map(s => s.length));
type.longestStringLength = Math.max(...type.map(s => s.length));
id = id.map((s,_,a) => s + " ".repeat(a.longestStringLength-s.length));
type = type.map((s,_,a) => " ".repeat(a.longestStringLength-s.length) + s);
console.log(id,type);
Use \t instead of space while concatenating to make it aligned.
Why don't you just add tab '\t' and it will give you the desired output. Or you can append fixed number of spaces between the two array items.

Categories

Resources