1

If I have a Javascript array filled with say 10 numbers. For example (10,11,12,13,14,15,16,17,18,19) And I want to take a variable which has a value of say 20, and check to see whether any of the elements in the array are larger than 20. Because I will be comparing many arrays filled with numbers and will not know what numbers they contain.

How do you take 20 and then get Javascript to test each number in the array to find out if it is larger than 20 or not.

I know you can say something like:

var x = 20;
if (  x > myArray[0] && 
  x > myArray[1]     

etc. etc. but that could mean typing out a long list of element checks. Is there a simple way like check from start index [0] to [10] or something?

3
  • 4
    Haven't you heard of for loops? Commented Oct 18, 2012 at 11:00
  • Well, even if you haven't, you can use a while loop, too. (Sadly, there isn't something called goto in JavaScript...) Commented Oct 18, 2012 at 11:01
  • For loop, .sort() and .slice() might just prove useful Commented Oct 18, 2012 at 11:02

6 Answers 6

1

You can use .some():

if (myArray.some(function(x) {return x > 20;}))
    // do something

It is not supported in all browsers, but you can easily shim it. Also, libraries have helper functions like this, e.g. Underscore's any.

Sign up to request clarification or add additional context in comments.

Comments

0

Use a for loop.

for (var i = 0; i < myArray.length; i++) {
    if (x > myArray[i]) {
         // whatever
    }
}

4 Comments

tips : write var len = myArray.length in first argument along with var iand then use len in 2nd argument in for loop
@diEcho, thats a micro-optimization which imo sacrifices readability.
Thanks that simple code is very helpful. I was trying to think how I could do it with a for loop, but couldn't work it out. I am pretty new to arrays though. Thanks also to everyone for all the extra replies, I will sure keep them for reference as I keep learning.
If there is anything else I should do like tick this or that, or respond to something please tell me here as I am new around here.
0
var x = 20;
var myArray = [10,11,12,13,14,15,16,17,18,19];
var cnt=0;

for(var i = 0; i < myArray.length; i++) {
 if(myArray[i]>x) {
   cnt++;
 }
}

alert("Found "+cnt+" values greater than "+x+" in the array" );

1 Comment

Don't use for...in on arrays, that's a loop for objects
0

Try this:

function getValuesFrom(array,x)
{
    x = +(x);//coerce to number
    array.sort(function(a,b)
    {
        return (a > b ? 1 : -1);
    });//sort in ascending order
    for (var i = 0;i<array.length;i++)
    {
        if (+array[i] >= x)
        {
            return array.slice(i);//return all elements >= x
        }
    }
}
var myArray = [10,11,12,13,14,15,16,17,18,19];
var larger = getValuesFrom(myArray,15);
console.log(larger);//[15,16,17,18,19]
console.log(larger.length);//5

That should do it. Note: after passing the array to this function, you might find its order is changed, to avoid this:

function getValuesFrom(array,x)
{
    x = +(x);//coerce to number
    var tmpArray = array.slice(0);//copy array
    tmpArray.sort(function(a,b)
    {
        return (a > b ? 1 : -1);
    });//sort in ascending order
    for (var i = 0;i<tmpArray.length;i++)
    {
        if (+tmpArray[i] >= x)
        {
            return tmpArray.slice(i);//return all elements >= x
        }
    }
}

1 Comment

Instead of creating a new array, sorting it, and creating a subarray of the sorted one you want to use myArray.filter(function(x) {return x > 20;})?
0

I like using Object.prototype to extend the base functionality of JavaScript Objects. Just like the JS Frameworks prototype and MooTools do.

So introducing a new filter function to the JS Array-Object does not only solve your specific problem, but furthermore a whole class of Problems.

// extending the Array type with the new function 'filter'
// so all arrays have access to this function
// argument `fn` is a test-function which returns true or false
Array.prototype.filter = function(fn) {
    var filtered = []; // a new array for the filtered items
    for(var i = 0, len = this.length; i < len; i++) {
        var item = this[i];
        // store this item if fn returns true
        if( fn(item) ) filtered.push(item); 
    }
    return filtered;
}

// want to filter this array   
var myArr = [1,2,3,4,5,6];

// find items in myArr > 3
var myArrGt3 = myArr.filter(
    // this is the test function / must always return a bool
    function(item) {
        return item > 3;
    }
);

// testing output
document.write(JSON.stringify(myArrGt3)); // prints "[4,5,6]"

1 Comment

Neither of those libs extends Object.prototype. Also, you shouldn't overwrite Array.prototype.filter as there is already one, with even advanced options
0

You can use inArray method using jQuery.

Description: Search for a specified value within an array and return its index (or -1 if not found).

$.inArray( 5 + 5, [ 4, 5 , 7, 10 ] );  // output is 3

Example:

<script>
var arr = [ 4, "Pete", 8, "John" ];

jQuery.inArray( "John", arr ) // this returns 3(Index value of John)


</script>

Also with the help of for loop you can also loop them.

var array1=["fox","tiger","lion"];
var array2=["rat","cow","lion"];
for(i=0; i<array2.length; i++)
{
document.write(jQuery.inArray( array2[i], array1 ));
}

Output: -1 
        -1 
         2

Good day!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.