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
Solution 1:
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.
Solution 2:
Use ES6 Array.filter()
and arrow functions with expression body:
myArray.filter(x => x > 5)
A bit more concise than @Beauty's answer.
Solution 3:
Here a short way to write a filter. From an array of numbers it returns all values greater than 5.
myArray.filter((x) => { return x > 5; })
Usage example:
var filterResult = [1, 10, 4, 6].filter((x) => { return x > 5; });
console.log(filterResult); // returns [ 10, 6 ]
And here a filter for an array of objects, which checks a property condition.
myArray.filter((x) => { return x.myNumber > 5; })
Usage example:
var myArray = [{myNumber: 1, name: 'one'}, {myNumber: 3, name: 'tree'}, {myNumber: 6, name: 'six'}, {myNumber: 8, name: 'eight'}];
var result = myArray.filter((x) => { return x.myNumber > 5; });
console.log(result); // returns [ { myNumber: 6, name: 'six' }, { myNumber: 8, name: 'eight' } ]
Solution 4:
You can use for ... in
in JavaScript:
for (var key in array) {
if (/* some condition */) {
// ...
}
}
As of JavaScript 1.6, you can use this, too:
for each (var element in array) {
// ...
}
These are mainly meant to traverse object properties. You should consider to simply use your for
-loop.
EDIT: You could use a JavaScript framework like jQuery to eliminate these cross-browser problems. Give it a try. Its $.each()
-method does the job.
Solution 5:
You can use Array.prototype.find, wich does exactly what you want, returns the first element fullfilling the condition. Example:
> ([4, {a:7}, 7, {a:5, k:'r'}, 8]).find(o => o.a == 5)
{a:5, k:'r'}