0

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 !!

kevin ternet
  • 4,514
  • 2
  • 19
  • 27
Mer
  • 93
  • 1
  • 1
  • 11
  • It's unclear what you're asking for here. Once you break the array up into sets of 3 elements what do you want to do with them? Please provide an example input and output. – Damon Nov 12 '16 at 16:33
  • Are you saying that your code _already works_, but that you _dislike_ using `ar.slice(0, 3)`? Is it for performance reasons? `ar.slice()` is [likely the fastest way](http://stackoverflow.com/a/20547803/5257399) to duplicate part of your array. – Birchlabs Nov 12 '16 at 16:35

3 Answers3

1

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;
    }
});
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

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));
}
Abk
  • 2,137
  • 1
  • 23
  • 33
0

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;
}
Jason Cust
  • 10,743
  • 2
  • 33
  • 45