Fetching JavaScript array elements after consecutive occurrence of an element -


i have javascript array like:

var myarray = ['a', 'x', 'b', 'x', 'x', 'p', 'y', 'x', 'x', 'b', 'x', 'x']; 

i want fetch elements of array come after 2 consequent occurrences of particular element.

i.e. in above array, want fetch elements come after consequent 'x', 'x'

so output should be:

'p' 'b' 

i have solution :

var arrlength = myarray.length; (var = 0; < arrlength; i++) {     if(i+2 < arrlength && myarray[i] == 'x' && myarray[i+1] == 'x') {         console.log(myarray[i+2]);     } }; 

this satisfies needs, not generic.

for eg. if have check 3 consequent occurrences, again have add condition inside if myarray[i+2] == 'x' , on.

could provide better way fetch elements?

the functional way use recursion. es6 spread, can pretty emulate terseness of 'functional' language :-)

var myarray = ['a', 'x', 'b', 'x', 'x', 'p', 'y', 'x', 'x', 'b', 'x', 'x'];  function reducer(acc, xs) {     if (xs.length > 2) {         if (xs[0] === xs[1]) {             // add third element accumulator             // remove first 3 elements xs             // return reducer([xs[2], ...acc], xs.slice(3));             // or per nina's question below             return reducer([xs[2], ...acc], xs.slice(1));         } else {             // remove first element xs , recurse             return reducer(acc, xs.slice(1))         }     } else {         return acc;     } }  console.log(reducer([], myarray)); 

Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -