Optimize javascript if else 18 times [closed] - javascript

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
I am trying to create a golf scorecard and are able to do so like this:
if(i == 0){
totalpoints = pp0[0];
} else if(i == 1){
totalpoints = pp0[0]+pp0[1];
} else if(i == 2){
totalpoints = pp0[0]+pp0[1]+pp0[2];
} else if(i == 3){
totalpoints = pp0[0]+pp0[1]+pp0[2]+pp0[3];
}....
This off course goes on 18 times? making each line even longer... How can I do this more optimized?
Hoping for help and thanks in advance :-)

Where i is your existing variable:
var totalpoints = 0;
for(var j = 0; j < i; j++) {
totalpoints += pp0[j];
}
This is pretty much what arrays were invented for!

you can use this:
for (var j=0;j<i+1;j++) {
totalpoints += pp0[j];
}

for (j=0; j<=i; j++) {
totalpoints += pp0[j];
}

basically what you are doing is doing a sum, so a doing a method might be a good start:
function sum(counter)
var sum =0;
for(var i = 0; i < counter ; i++) {
sum+= pp0[i];
}
return sum;
}

you can try writing a loop.
totalPoints = 0;
for(var i=0;i<j;i++)
{
totalPoints += pp0[i];
}

It looks like you just want to add up the first i values in the pp0 array, so use a loop:
var totalpoints = 0;
for (var index=0; index<i; index++) {
totalpoints += pp0[index]
}

It's like you're doing a sum, so you can use the built-in reduce function in JavaScript:
totalpoints = pp0.reduce(function (prev, cur) {
return prev + cur;
}, 0);
This will go through all elements in pp0 and return a sum. If, however, you want only the first n parts of pp0, use a slice:
totalpoints = pp0.slice(0, n).reduce(function (prev, cur) {
return prev + cur;
}, 0);
See mdn for details and browser compatibility.
Note:
This solution assumes that you're using a real array (Array.isArray()) and relatively new browser features.

Related

JavaScript Odd Number Sorter Coding Challenge [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
Ok so I'm working on learning JavaScript and I came across a Coding Challenge question which I can not solve. It gives me the outline/skeleton of the format I should use and wants me to find the odd numbers from 1-5000.
Starting with the basic function given below, write a function called sumOddNumbers that will print to the console and return the sum of all the odd numbers from 1 to 5000. Consider using a loop, and don't forget to call the function afterwards!
~ Format ~
function sumOddNumbers() {
var sum = 0;
// Your code here
console.log(sum);
return sum;
}
There is no need for a loop:
console.log(5000**2/4);
If 5000 is a dynamic input to your function, then the formula is as follows:
function sumOddNumbers(n) {
return (n + n%2)**2/4;
}
console.log(sumOddNumbers(5000));
If really it has to be done with a loop, and according to the template (which is not very nice BTW):
function sumOddNumbers() {
var sum = 0;
for (let i = 1; i <= 5000; i+=2) {
sum += i;
}
console.log(sum);
return sum;
}
sumOddNumbers();
let sum = 0;
for (let i = 1; i < 5000; i += 2) {
sum += i;
}
let sum = 0;
for (let i = 0; i < 5000; i++) {
if (i % 2 !== 0) {
sum += i;
}
}
function sumOddNumbers(max) {
let sum = 0;
for(let i = 1; i <= max; i+=2){
sum += i;
}
console.log(sum);
return sum;
}
sumOddNumbers(5000);

Delete identical elements from string [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Got string, need to delete same words from there.
Here is my code. I tried to split string into array and then sort but it didn't work. It didn't even go through my if. I would like to hear your advice and maybe working code :)
var str = "I wont go anywhere as soon as I wont go there";
var array = str.split(" ");
document.getElementsByTagName('p')[0].innerHTML = str;
document.getElementsByTagName('p')[1].innerHTML = array;
document.getElementsByTagName('button')[0].onclick = function () {
for (var i = 0; i < array.length; i++) {
if (array[i] == array[i + 1]) {
array.splice(i, 1);
}
}
document.getElementsByTagName('p')[2].innerHTML = array;
}
If you like one-lines try this
var reducedString = array.reduce(function(out, s) {
return out.indexOf(s) == -1 ? out + ' ' + s : out;
},'').substring(1);
or in ES6
var reducedString = array.reduce( (out, s) => out.indexOf(s) == -1 ? out + ' ' + s : out);
Your problem is that you don't check every array element with every other array element.
Your code:
for (var i = 0; i < array.length; i++) {
if (array[i] == array[i + 1]) {
array.splice(i, 1);
}
}
Just checks array elements in sequence.
Try:
for (var i = 0; i < array.length; i++) {
for(var j = 0; j < array.length; j++){
if (array[i] == array[j] && i != j) {
array.splice(i, 1);
}
}
}
You can use an ES6 Set with the spread syntax after splitting the sentance:
const str = "I wont go anywhere as soon as I wont go there";
const unique = [...new Set(str.split(' '))].join(' ');
console.log(unique);
In ES5 you can use Array#reduce with a dictionary object.
var str = "I wont go anywhere as soon as I wont go there";
var dict = Object.create(null); // creates an empty object, without inherited properties and methods
var unique = str.split(' ').reduce(function(arr, w) {
if(!dict[w]) {
arr.push(w);
dict[w] = true;
}
return arr;
}, []).join(' ');
console.log(unique);
You can just replace the substring you are searching for
var ret = "data-123".replace('data-','');
console.log(ret);

Find the next highest number in array [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have an array of numbers and a value. I'd like to find the numbers around the value. The most important is the highest value but I need both.
var array = [2,4,5,8,11];
var value = 9;
The result I need should be : 8 and 11.
How can I do that?
Thanks.
Just write a simple for-loop searching for each of the values.
So for example:
function findNumbers(arr, num){
var low = num + 1; //largest number lower than num, set initial value above num
var high = num - 1; //smallest number higher than num, set initial value below num
for(var i = 0; i < arr.length; i ++){
if(arr[i] > low && arr[i] < num){
low = arr[i];
}
if(arr[i] < high && arr[i] > num){
high = arr[i];
}
}
//optional check to see if low/high exists
if(low > num){
low = -1; //not found
}
if(high < num){
high = -1; //not found
}
return [low,high];
}
and there you go. This works whether or not arr is sorted.
This help you :
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
var array = [2,4,5,8,11];
var value = 9;
var min,max;
fun();
function fun() {
var sortArray = array.sort(function(a,b){return a-b});
for(var i=0; i<sortArray.length;i++) {
if (sortArray[i] < value)
min = sortArray[i];
if (sortArray[i] > value)
max = sortArray[i];
}
alert(min + " , " + max);
}
</script>
</body>
</html>
Looking at your question looks like you are still learning jquery.However I am sure you will get good suggestions here.
Here is an example with your test case,I am leaving the explanation on you so that you can study each line and learn.
var myArray = [2, 4, 5, 8, 11];
var myValue = 9;
function BiggerThan(inArray) {
return inArray > myValue;
}
function LesserThan(inArray) {
return inArray < myValue;
}
var arrBiggerElements = myArray.filter(BiggerThan);
var nextElement = Math.min.apply(null, arrBiggerElements);
alert(nextElement);
var arrLesserElements = myArray.filter(LesserThan);
var prevElement = Math.max.apply(null, arrLesserElements);
alert(prevElement);

Javascript loop. What am I doing wrong?

Trying to make a loop that outputs 2 to the power of 0-31. So far I only have it giving me 2 to the power of 31. What am I doing wrong?
function findPower()
{
var answer=0;
for(var i=0;i<=31;i++)
{
answer=Math.pow(2,i);
}
document.getElementById("output").innerHTML=answer;
}
Because in the loop in each iteration you are overriding the value of answer, so at the end it will have the value of last iteration only.
If you want to iterate the value of each number, then an easy solution is to push them to an array and after the loop join them to create the answer string as below
function findPower() {
var answer = [];
for (var i = 0; i <= 31; i++) {
answer.push(Math.pow(2, i));
}
document.getElementById("output").innerHTML = answer.join(', ');
}
function findPower() {
var answer = [];
for (var i = 0; i <= 31; i++) {
answer.push(Math.pow(2, i));
}
document.getElementById("output").innerHTML = answer.join(', ');
}
findPower();
<div id="output"></div>
You statement inside loop "document.getElementById("output").innerHTML=answer;" is overriding previous value so you are getting the last value. So what I did is to concatinate the values instead of overriding previous values
it should like following
function findPower() {
var answer = 0;
for (var i = 0; i <= 31; i++) {
answer = Math.pow(2, i);
document.getElementById("output").innerHTML = document.getElementById("output").innerHTML + "," + answer
}
}
<body onload="return findPower();">
</body>
<span id="output"></span>
If I get you right you want to calculate a sum of powers of 2:
for (var i = 0; i <= 31; i++) {
answer += Math.pow(2, i);
}
Notice the "+" sign. Writing:
answer += Math.pow(2, i);
Is the same as writing:
answer = answer + Math.pow(2, i);
Maybe it's better and faster.
function findPower() {
var answer = [];
var pow = 1;
answer.push(pow);
for (var i = 1; i <= 31; i++) {
pow *= 2;
answer.push(pow);
}
document.getElementById("output").innerHTML = answer.join(', ');
}

A quite weird array [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
Here is my problem, I'm programming a game and I need to use a very simple array, the problem is that I create it, everything's ok, and the next line, the values of an entire line in the array change and I don't understand why, here is my code :
var ciblesPossibles = new Array();
for (var i = 0; i < 2; i++) {
for (var j = 0; j < 5; j++) {
ciblesPossibles[i,j] = 1 + portee(i, j, ID, pos, carte.effet.portee) + duBonCote(i, ID, carte.effet.ciblesLegales);
}
console.log('1/ ciblesPossibles['+i+',x] = ' + ciblesPossibles[i,0] + ciblesPossibles[i,1] + ciblesPossibles[i,2] + ciblesPossibles[i,3] + ciblesPossibles[i,4]);
}
for (i = 0; i < 2; i++) {
console.log('2/ ciblesPossibles['+i+',x] = ' + ciblesPossibles[i,0] + ciblesPossibles[i,1] + ciblesPossibles[i,2] + ciblesPossibles[i,3] + ciblesPossibles[i,4]);
}
var max = maxTab(ciblesPossibles);
for (i = 0; i < 2; i++) {
for (j = 0; j < 5; j++) {
ciblesPossibles[i,j] = Math.floor(ciblesPossibles[i,j] / max);
console.log(ciblesPossibles[i,j]);
}
}
portee() and duBonCote() are two functions which return just 1 or 0.
When I'm at the console.log('/1...'), I have something like 33222 and 22211 (it's what I want), but when I'm at the console.log('/2...'), I have 22211 and 22211 ... What can make the first line change in my array ?
Regards
Two dimensional arrays are accessed as a[i][j], not a[i,j].
The latter will be treated as a use of the comma operator, and evaluates to just a[j], i.e. a one-dimensional matrix.
You'll be wanting something more like:
var ciblesPossibles = []; // create array to hold rows - NB: not "new Array():
for (var i = 0; i < 2; i++) {
ciblesPossibles[i] = []; // create the individual row
for (var j = 0; j < 5; j++) {
ciblesPossibles[i][j] = ...
}
}

Categories