简体   繁体   中英

Take three elements at a time from array

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; } }); 

Probably this is what you need.

Check out the demo below

 var ar = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm']; for(var i = 0; i < ar.length; i+=3){ console.log(ar.slice(i, i+3)); } 

It sounds like some you want an iterator of sorts. An explicit example would be something like:

 var input = [0, 1, 2, 3, 4, 5, 6, 7, 8]; // console.log(checkChunks(input, 2, checkChunkSum(10))); console.log(checkChunks(input, 3, checkChunkSum(10))); function checkChunks(arr, chunkLength, checker) { var startIndex = 0; var chunk; while ((chunk = arr.slice(startIndex, startIndex += chunkLength)).length) { var result = checker(chunk); console.log('Checking chunk: ', chunk); if (result !== false) { return { chunk: chunk, result: result }; } } return false; } function checkChunkSum(max) { return function checkSum(arr) { return arr.reduce(sum, 0) > max; } } function sum(a, b) { return a + b; } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM