This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How might I find the largest number contained in a JavaScript array?
I am having trouble getting this code to work. I have been at it for a while trying to figure it out. When I look at the console it just displays 0. What did I do wrong?
Here is my code:
var array = [3 , 6, 2, 56, 32, 5, 89, 32];
var largest= 0;
for (i=0; i<=largest;i++){
if (array>largest) {
var largest=array[i];
}
}
console.log(largest);
var arr = [3, 6, 2, 56, 32, 5, 89, 32];
var largest = arr[0];
for (var i = 0; i < arr.length; i++) {
if (largest < arr[i] ) {
largest = arr[i];
}
}
console.log(largest);
You need to define i or else it become a global variable.
Don't redefine largest in the loop.
Since you're looping through the array, use i < array.length instead of i <= largest.
Since you're comparing each of the items in the array to largest, use if(largest < array[i]) instead of if(array > largest)
You should set largest equal to the first element in the array because what if all the numbers are negative?
array is a bad variable name because it's too similar to Array (the array constructor). Try arr instead.
One liner:
var largest = Math.max.apply(0, array);
More info here: Javascript max() function for 3 numbers
The code below is fixed and should work. The problem was that in this line if (array>largest) { You were not providing the index of the array. By changing the code to this if (array[i]>largest) { it works. Notice that I added the [i] to the end of array in the if statement.
var array = [3 , 6, 2, 56, 32, 5, 89, 32];
var largest= 0;
for (i=0; i<array.length; i++){
if (array[i]>largest) {
largest=array[i];
}
}
console.log(largest);
Just one line :)
var array = [3 , 6, 2, 56, 32, 5, 89, 32],
largest = array.sort((a,b)=>a-b).reverse()[0];
or even better
...
largest = array.sort((a,b)=>a-b)[array.length - 1];
UPD, all code above is sucks when you add for example 9 in array my guess because by default numbers treated as strings in sort, there is better version
var array = [3 , 6, 2, 56, 32, 5, 89, 32, 9], largest;
array.sort(function(a, b) {
largest = a > b ? a: b;
});
although in performance wise forEach loop suggested in comments are better
http://jsperf.com/array-sorting-javascript-stack
UPD2, okay, code above has some bad parts in it, so will not work as expected. Another try:
array.sort(function(a, b) {
return a - b;
});
largest = array[array.length - 1];
You have a few small mistakes. First:
if (array>largest) {
It should instead be:
if ( array[i]>largest) {
Second:
for ( i = 0; i <= largest; i++) {
should be
for (i = 0; i <= array.length; i++) {
var array = [3 , 6, 2, 56, 32, 5, 89, 32];
var largest= array[0];
for (i=0; i<=largest;i++){
if (array[i]>largest) {
largest=array[i];
}
}
You have two issues in your code. First, array>largest should be array[i]>largest. Second, you are declaring a new largest variable inside the if which isn't the same as the one outside. Remove var from the assignment of the new largest value.
Related
Where is the mistake? I want to sum every number in the array. The alert says NaN.
var numbers = [10, 42, 5, 87, 61, 34, 99];
var i = 0;
var e = 0;
while(i <= numbers.length) {
e = e + numbers[i];
i++;
}
alert(e);
This line is the reason:
while(i <= numbers.length) {
Arrays are 0 index so you can go from index 0 (inclusive) until numbers.length (exclusive). You are going beyond that limit, causing you to access an element that isn't defined at the given index. You must do this instead:
while(i < numbers.length) {
Alternatively using the ES2015 syntax you can do it like this.
let numbers = [10, 42, 5, 87, 61, 34, 99];
let sum = numbers.reduce((a,b) => a + b);
You can read about Array.prototype.reduce(accumulator, element, callback, startingValue) here.
Your condition is wrong, just use < insteead of <=
while(i < numbers.length)
There's a few ways you can improve this. The first is that you want to change your condition to i < numbers.length, not i <= numbers.length. As you've written it, the last number will never be counted.
Another way you can improve this is using the += notation -- there's no need to write e = e + numbers[i] when you can write e += numbers[i].
You could íterate from the end of the array with a post increment and a check for truthyness in the while condition.
Inside just add the item.
var numbers = [10, 42, 5, 87, 61, 34, 99],
i = numbers.length,
e = 0;
while (i--) {
e += numbers[i];
}
console.log(e);
The problem is in array length You are checking because array index starts with 0. In that way when doing:
i <= numbers.length
You are checking [0: 10, 1: 42, 2: 5, 3: 87, 4: 61, 5: 34, 6: 99, 7:???] because numbers length is 7. To solve it just do:
i < numbers.length
where You don't check non existing number in array.
Here is how we were thought in school:
//main code//
var numbers = [10, 42, 5, 87, 61, 34, 99];
var result = sumIntArray(numbers);
//end of main code//
function sumIntArray(array){
var result = 0;
for (var i = 0; i < array.length; i++) {
if (array[i].isInteger()) {
result += array[i];
} else {
if (i === 0) {
alert("1st object in array is not number, will skip...");
}
else if (i === 1) {
alert("2nd object in array is not number, will skip...");
}
else if (i === 2){
alert("3rd object in array is not number, will skip...");
}
else {
alert((i+1).toString() + "th object in array is not number, will skip...");
}
}
}
return result;
}
The for loop adds this i++ You make in a while loop and makes code a bit more clear.
No need for declaring i in main code :)
Always make functions to simplify main code.
Make function that will never make mistake even if somebody wants to break The logic.
Although don't make school break Your creativity, Your code is great! :)
I'm trying to make a new array from an if conditional inside a for loop in JavaScript. So far the new array returns undefined when:
if( numbers[i] <= num)
I need to return all elements that are less or equal to the value of num and create a new array from them. Can someone tell me what I'm doing wrong?
function search(num, numbers) {
for (i = 0; i < numbers.length; i++){
var x = [];
if( numbers[i] <= num){
x.push(numbers[i]);}
}
return x;
}
(search(14, [7, 3, 23, 9, 14, 20, 7])
You should use array.filter
function search(num, numbers) {
return numbers.filter(function(n) { return n <= num });
}
search(5, [1,3,44,7,10]) //returns [1,3]
The core issue with your code above is that you declare var x = [] in every iteration of the for loop - it's overwritten each time.
There's no array called "prices". You should replace "prices"
with "numbers". This is why you get undefined.
Move x=[] outside the for loop. Otherwise, x is going to be instantiated with an empty array every time it goes through the for loop. Your code seems to erase x's contents every time your function iterates through the loop.
function search(num, numbers) {
var x = [];
for (i = 0; i < numbers.length; i++){
if( numbers[i] <= num){
x.push(numbers[i]);}
}
return x;
}
$('p').text(search(14, [7, 3, 23, 9, 14, 20, 7]));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<p></p>
See fiddle
looks like you are iterating over another array "Prices" whose length may be greater than numbers array that is why you are getting undefined.
Move x=[] outside the for loop as it is getting reset for each value of for loop
"prices.length"
You can use underscore.js filter function for this
bigValues = function(array){
return _.filter(array, function(element){
return element > 10;
});
}
var array = [ 1, 2, 3, 10, 11, 23 ];
var bigResult = bigValues(array);
I search everywhere here but couldn't find the answer...only some pieces of it..
I got an interview question...
You have an array and it's array.length=9. You have 10 numbers, from 1 to 10. Put those numbers randomly to Array. How to find/return the number what leftover and not got to the Array.
Any solutions?
Try the following code:
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
var chosen = [];
for(var i = 0; i < 9; i ++){
var index = Math.floor((Math.random() * numbers.length) + 1)-1;
chosen.push(numbers[index]);
numbers.splice(index, 1);
}
document.write(JSON.stringify(chosen)+"<br>");
document.write(numbers);
using array.indexOf() method you can do it.
first creat random array arr then do this:
for(var i=1;i<=10;i++){
if(arr.indexOf(i)==-1){
console.log(i+'is not in the array');
return i;
}
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
i have a sorted array of numbers [2, 5, 12, 34, 56]
and a random number "17".
I need the index of the next highest number from my array. In this case i want to recieve "3" as it is the index of "34" which is the next highest number in my array.
any ideas?
A function that meets the requirements can be as simple as:
function getNextHighestIndex(arr, value) {
var i = arr.length;
while (arr[--i] > value);
return ++i;
}
getNextHighestIndex([2, 5, 12, 34, 56], 17); // 3
getNextHighestIndex([2, 5, 12, 34, 56], 100); // 5
getNextHighestIndex([2, 5, 12, 34, 56], 0); // 0
If there is no value in the array that is higher than the supplied value, it will return the length of the array. If all values in the array are higher, it will return 0.
Running with vzwick's suggestion, you could do this quite neatly with underscore's filter and indexOf methods:
function getNextHighestIndex(arr, number) {
return _.indexOf(arr, _.filter(arr, function(val) {
return val > number
})[0]);
}
getNextHighestIndex([2, 5, 12, 34, 56], 17);
Or vanilla JavaScript:
function getNextHighestIndex(arr, number) {
for (var i = 0; i < arr.length; i ++) {
if (arr[i] > number) {
return i;
}
}
}
getNextHighestIndex([2, 5, 12, 34, 56], 17);
This code will return the index you are looking for, and will return -1 if there is no number greater in the array.
function findNextHighest(array_input, compare_num){
for (i=0;i<array_input.length;i++){
if (array_input[i] > compare_num){
return i;
}
}
return -1; // Value returned if no highest number found in the array
}
See: http://jsfiddle.net/w42wE/3/ (click run)
var MyArray = [2, 5, 12, 34, 56]
var RandomNumber = 17;
var MinGreaterThanPos;
for (var i =0; i < MyArray.length; i++) {
if (MyArray[i] <= RandomNumber)
continue;
if (typeof(MinGreaterThanPos) == 'undefined' || MyArray[i] < MinGreaterThanPos)
{
MinGreaterThanPos = i;
}
}
alert(MinGreaterThanPos);
for (var i=0; i<ary.length; i++;) {
if (ary[i] > target)
return i;
}
var myArray = [2, 5, 12, 34, 56],
randomNumber = 17;
var result = $(myArray)
.map(function(i){ return (this > randomNumber) ? i : null })
.get() // un-wraps the jQuery object to a proper Array
.shift();
That being said, OP might want to look into underscore.js as a leaner alternative - honestly, jQuery is a bit of an overkill for the task.
If you want something a bit more sophisticated, implement a divide&conquer search algorythm:
function find_next(list, query) {
var pointer_upper = list.length - 1;
var pointer_lower = 0;
var pointer_tmp;
while (pointer_upper - pointer_lower > 1) {
pointer_tmp = Math.ceil((pointer_upper + pointer_lower)/2)
if (list[pointer_tmp] <= query) {
pointer_lower = pointer_tmp;
} else {
pointer_upper = pointer_tmp;
}
}
return pointer_lower + 1;
}
find_next([2, 5, 12, 34, 56], 17); // returns 3
Note: it is possible that this function will return a result that is less then the query (if all the elements in list are less then query). So maybe you would like to check for that before returning.
Here is the way I am using to return duplicate elements.. But I am facing most dangerous performance issues like browser close etc when my array have large number of items with long texts..
var arr = [9, 9, 111, 2, 3, 4, 4, 5, 7];
var sorted_arr = arr.sort();
var results = [];
for (var i = 0; i < arr.length - 1; i++) {
if (sorted_arr[i + 1] == sorted_arr[i]) {
results.push(sorted_arr[i]);
}
}
alert(results);
Please suggest me a best way of doing this
i don't get exactly what you want, but if you need to return duplicates you could use a cache object. this works with number or string or whatever.
var arr = [9, 9, 111, 2, 3, 4, 4, 5, 7];
var cache = {};
var results = [];
for (var i = 0, len = arr.length; i < len; i++) {
if(cache[arr[i]] === true){
results.push(arr[i]);
}else{
cache[arr[i]] = true;
}
}
console.log(results);//returns an array with 9 and 4
Of course you can do other things like deleting multiple items etc. etc.
EDIT - i've written a blog entry on how to remove duplicates from an array
If you have array filter, you also have indexOf and lastIndexOf,
and you can return the duplicates without doing the sort.
var results, arr= [9, 9, 111, 2, 3, 4, 4, 5, 4, 7];
if(arr.filter){
results= arr.filter(function(itm, i){
return arr.lastIndexOf(itm)== i && arr.indexOf(itm)!= i;
});
}
else// use your loop method
alert(results)
/* returned value: (Array)
9,4
*/
Assuming Nicola's solution doesn't work for you (since it uses about as much memory as the original solution: two elements stored per element in the input, worst-case), you can use the slower process of repeatedly searching your input.
This requires the Array.indexOf method from ECMAScript 5. A lot of browsers have it. For alternatives, see How do I check if an array includes an object in JavaScript?.
var arr = [9, 9, 111, 2, 3, 4, 4, 5, 7];
var results = [];
for (var i = 0, len = arr.length - 1; i < len; i++) {
if((results.indexOf(arr[i]) == -1) && (arr.indexOf(arr[i], i + 1) != -1)) {
results.push(arr[i]);
}
}
console.log(results);
This uses no more memory than the input arr plus the output results, but it's an O(N^2) algorithm and doesn't have to modify arr.
Your method relies on a sort, which may or may not be one reason you run out of space/time.
The canonical way to remove duplicates is to keep a hash map of the keys (an object in JS). The object keys you get back won't necessarily be in the order you want; you don't specify if you want the results ordered as well, but they are now.
You could null out the original array, since you no longer require it; when it gets collected is up to the JS engine though.
You could remove duplicates "in place" by keeping a "current index" into the sorted array, and increment it only when you move a non-duplicated element "down" from the counter index, then truncate the array that you return.
Combining the last two techniques should mean that in general you'll only have a single array with a valid reference.
Edit Example. Setting length explicitly, as .slice() creates a new array.
var have = {};
var arr = [9, 9, 111, 2, 3, 4, 4, 5, 7];
arr = arr.sort();
for (var rIdx = 0, i = 0; i < arr.length; i++) {
if (have[arr[i]]) {
arr[rIdx++] = arr[i];
} else {
have[arr[i]] = true;
}
}
arr.length = rIdx;
console.log(arr);