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 conditi
Write a generic function that accepts various conditions:
function array_only(arr, condition) {
hold_test=[]
arr.map(function(e, i) {if(eval(condition)){hold_test.push(e)}})
return(hold_test)
}
Example:
use_array = ['hello', 'go_there', 'now', 'go_here', 'hello.png', 'gogo.log', 'hoho.png']
Usage:
return only elements containing .log extension:
array_only(use_array, "e.includes('.log')")
[ 'gogo.log' ]
return only elements containing .png extension:
array_only(use_array, "e.includes('.png')")
[ 'hello.png', 'hoho.png' ]
return only elements NOT containing .png extension:
array_only(use_array, "!e.includes('.png')")
[ 'hello', 'go_there', 'now', 'go_here', 'gogo.log' ]
return elements containing set of extensions and prefixes:
array_only(use_array, "['go_', '.png', '.log'].some(el => e.includes(el))")
[ 'go_there', 'go_here', 'hello.png', 'gogo.log', 'hoho.png' ]
You can easily pass MULTIPLE CONDITIONS
return all png files that are less than 9 characters long:
array_only(use_array, "e.includes('.png') && e.length<9")
[ 'hoho.png' ]
Just came across the same problem. Tim Down came close, he just needed a wrapper to the length of the filtered array:
// count elements fulfilling a condition
Array.prototype.count = function (f) {
return this.filter(f).length;
};
Usage:
// get the answer weight from the question's values array
var w = Math.pow(q.values.count(function(v) { return v !== -1; }), -1);
I hope that answers this long standing question!
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.
Problem:
I need to know if a client set exists for any PJ client.
Solution:
function deveExibirLista(lst: Clientes[]){
return lst.some(cli => cli.Documento === 14);
}
It's return boolean
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'}
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.