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);
Related
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);
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am working on a piece of code which make an array full of numbers with the amount of numbers i want, but instead of this beeing static with 16 numbers i tried to change 16 to a variable but the math.floor/randome cant read it it only spits out Not a number wierdly enough.
EDIT: with 16 put in it works, but i cant use a variable (declared in the same function ofc)after i console.log the variable it shows it as a number but then my browser freezes
Is There anyone who knows how to change this
while(arr.length < pictures.length) {
var randomenumber = Math.floor((Math.random()* 16));
if(arr.indexOf(randomenumber) > -1) {
continue;
}
arr[arr.length] = randomenumber;
}
//cheat sheet
for(var i = 0; i < arr.length ; i++) {
document.write(arr[i]);
document.write("<br/>");
}
I don't see any issues if you use var length = 16 and Math.floor((Math.random() * length)).
Working snippet:
var arr = [], length = 16;
while(arr.length < length) {
var randomenumber = Math.floor((Math.random() * length));
if(arr.indexOf(randomenumber) > -1) {
continue;
}
arr[arr.length] = randomenumber;
}
//cheat sheet
for(var i = 0; i < arr.length ; i++) {
document.write(arr[i]);
document.write("<br/>");
}
You will need to parse it in integer using parseInt.
var num = 16;
var randomenumber = Math.floor((Math.random() * parseInt(num)));
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 6 years ago.
Improve this question
so this is what I've achieved so far
function arrayMode(sequence) {
var arr= [];
var mostFreq = 1;
for(var i = 1; i <= 10; i++)
arr[i] = 0;
for(var i = 0 ; i < sequence.length; i++)
arr[sequence[i]]++;
for(var i = 1; i < 10; i++){
if( arr[i] > arr[mostFreq])
mostFreq = i;
}
return mostFreq;
}
so the scope for my case are
The sequence value is >= 1 and <=10
The sequence length is > 0
The sequence is an array of integer
Example 1
Input : sequence = [1, 10, 10]
Output : 10
Example 2
Input : sequence = [1, 3, 3, 3, 1]
Output : 3
It seems easy, I've tried to figure out but I cant find where is the mistake in my code, It's seems legit for me
As suggested by Maxim Krizhanovsky, the last loop should go from 1 to 10 instead of to sequence.length. Here is the working code
function arrayMode(sequence) {
var arr= [];
var mostFreq = 1;
for(var i = 0; i <= 10; i++)
arr.push(0);
for(var i = 0 ; i < sequence.length; i++)
arr[sequence[i]]++;
for(var i = 1; i <= 10; i++){
if( arr[i] > arr[mostFreq])
mostFreq = i;
}
return mostFreq;
}
The output is 10 and 3 respectively to your input.
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 8 years ago.
Improve this question
I have an array and direction variable for example:
var fruits = ["apple","banana","cherry"];
var direction = 1;
//1 => forward; -1 => backwards;
then to call it I might say
index = **SOME MATHS HERE**
var fruit = fruits[index]
So the aim is to have a loop that can go backwards and forwards through the array. I want to have a for loop that iterates through the array. I know I can do this using an if loop saying
if(direction < 0){//backwards} kind of thing but that would mean two lots of code when I can make it one using a clever maths operation to iterate through it.
Something like this would work:
var fruits = ["apple","banana","cherry"];
var direction = 1; // or -1
var i = direction > 0 ? 0 : fruits.length - 1,
stop = direction > 0 ? fruits.length : -1;
for (; i != stop; i += direction)
console.log(i, fruits[i]);
var fruits = ["apple", "banana", "cherry"];
function iterate(direction) {
var results = $("#results").empty();
var i = direction > 0 ? 0 : fruits.length - 1,
stop = direction > 0 ? fruits.length : -1;
for (; i != stop; i += direction)
$("<span>").text(i + ": " + fruits[i] + "\n").appendTo(results);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<button onclick="iterate(1)">Forward</button>
<button onclick="iterate(-1)">Backward</button>
<pre id="results" />
Just make a function.
var fruits = ["apple","banana","cherry"];
var direction = 1;
function iterate(arr, direction, callback){
if(direction === 1){
console.log("Forwards");
for(var i = 0; i < arr.length; i++){
//Iterate through array regularly
if(callback !== undefined){
callback(arr[i]);
}
}
}
else{
console.log("Backwards");
for(var i = arr.length - 1; i >= 0; i--){
//Iterate through array backwards
if(callback !== undefined){
callback(arr[i]);
}
}
}
}
iterate(fruits, direction, function(a){
console.log(a);
});
iterate(fruits, -direction, function(a){
console.log(a);
});
See this jsfiddle
Here's a generic "bi-directional" loop:
function bdLoop (step, amount[, additional arguments]) {
var n = (step < 0) ? amount - 1 : 0,
x, xstep = Math.abs(step);
for (x = 0; x < amount; x += xstep, n += step) {
// x always equals to 0 .. amount stepped by xstep
// n equals to 0 .. amount or amount .. 0 stepped by step, depends on direction (±step)
}
return[ results];
}
Within the loop you can refer to variables in the outer scope, handle passed arguments, and also pass a function reference and call the passed function etc.
A live demo at jsFiddle.
How about reversing the array conditionally so it's not as much code since you seem to want to avoid that:
if (direction < 0) {
fruits.reverse();
}
Then, use your for loop and it will go backwards or forwards depending on the value of direction.
see http://jsfiddle.net/ZfL24/1/
var fruits = ["apple","banana","cherry"];
var direction = 1;
for(var i = 0; i < fruits.length; i++) {
var fruit = fruits[direction === 1 ? i : fruits.length - (i + 1)];
}
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.