Friday, 15 May 2015

Array Pattern using Javascript -


I have an array: Myarray = [1,0,0,1,0,1,1, 0, 0]

I want to display elements of the array in pattern 1,0,1,0 ..

I tried to set a flag :

But the problem mismatched elements are not displayed in the output.

Any thoughts? Thank you.

1, 0 of new array 1, 0,. .. with length with myArray.length

  var NewArr = myArray. Map (function (e, i) {return 1 - (i% 2);});  

However, it can be more efficient to use the loop;

  var newArr = [], i = myArray.length; Whereas (i--> 0) newer [i] = 1 - (i% 2); NewArr; // [1, 0, 1, 0, 1, 0, 1, 0, 1]  

If you want to filter items that are constantly repeating, you can To remember what your last time was seen, the variable out of the filter function

  var newArray = (function () {var last; return myArray.filter (function (e) {var t = last ; Last = e; if (t === last) will return; Return;});} ());  

Or in a loop

  var newArr = [], last, i; For (i = 0; i & lt; myArray.length; ++ i) if (last! == myArray [i]) {final = myArray [i]; NewArr.push (last); } NewArr; // [1, 0, 1, 0, 1, 0]  

No comments:

Post a Comment