Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - get array element fulfilling a condition

I'm learning JavaScript using W3C and I didn't find an answer to this question.

I'm trying to make some manipulations on array elements which fulfill some condition.

Is there a way to do it other than running on the array elements in for loop? Maybe something like (in other languages):

foreach (object t in tArray)    if (t follows some condition...) t++; 

another thing, sometimes I want to use the element's value and sometimes I want to use it as a reference. what is the syntactical difference?

As well, I'll be happy for recommendations on more extensive sites to learn JavaScript from. thanks

like image 862
Day_Dreamer Avatar asked Sep 23 '10 09:09

Day_Dreamer


People also ask

How do you count the number of array elements matching a condition?

To count the elements in an array that match a condition: Use the filter() method to iterate over the array. On each iteration, check if the condition is met. Access the length property on the array to get the number of elements that match the condition.

How do you find an array condition?

To check if any value in JavaScript array satisfies the condition you can use Array. prototype. some() method. It returns true if any item in array satisfies the condition else returns false .

How do you check if an array contains a value in JavaScript?

JavaScript Array includes() The includes() method returns true if an array contains a specified value. The includes() method returns false if the value is not found.

How do I get an element from an array?

get() is an inbuilt method in Java and is used to return the element at a given index from the specified Array. Parameters : This method accepts two mandatory parameters: array: The object array whose index is to be returned.


1 Answers

In most browsers (not IE <= 8) arrays have a filter method, which doesn't do quite what you want but does create you an array of elements of the original array that satisfy a certain condition:

function isGreaterThanFive(x) {      return x > 5; }  [1, 10, 4, 6].filter(isGreaterThanFive); // Returns [10, 6] 

Mozilla Developer Network has a lot of good JavaScript resources.

like image 69
Tim Down Avatar answered Oct 03 '22 09:10

Tim Down