I have an array composed by nine elements:
var ar = ['a','a','a','a','a','a','a','a','a'];
I need to control three elements at a time by a function that returns a true or false. If the first returns true, the others do not have to execute in order to obtain just one true result.
var one = fun(ar.slice(0, 3));
if (one != false) document.write(one);
var two = fun(ar.slice(3, 6));
if (two != false) document.write(two);
var three = fun(ar.slice(6, 9));
if (three != false) document.write(three);
How can I simplify this process? To avoid the creation of a multiarray.
Thanks !!
You could use an array with the slicing paramters and iterate with Array#some
function fun(array) {
return array.reduce(function (a, b) { return a + b; }) > 10;
}
var ar = [0, 1, 2, 3, 4, 5, 6, 7, 8];
[0, 3, 6].some(function (a) {
var result = fun(ar.slice(a, a + 3));
if (result) {
console.log(a, result);
return true;
}
});