arrays - Loop Iteration avoid same indexes javascript -


i've scenario want walk in array in javascript, , checking if index matches option push or print once. ive following array:

["item1", "dummydata1", "dummydata2", "item2", "dummydata1", "dummydata2", "item3", "dummydata1", "dummydata2", "item4", "dummydata1", "dummydata2", "item4", "dummydata1", "dummydata2", "item4", "dummydata1", "dummydata2", "item4", "dummydata1", "dummydata2", "item5", "dummydata1", "dummydata2", "item5", "dummydata1", "dummydata2", "item6", "dummydata1", "dummydata2", "item7", "dummydata1", "dummydata2", "item7", "dummydata1", "dummydata2"] 

i want iterate array on every thing , if thing index matched previous leave else push in array. try tackle scenario using global variable setting wont help.

desired output:

[item1 ..... item7]      var currentitem ; var myarr; (var j = 1; j <= 100; j++) {   (var = 0; <= res[j].length-1; i++) {   var option1 = (res[j][i].match(/thing1-/));  var option2 = (res[j][i].match(/thing2-/));  var option3 = (res[j][i].match(/thing3-/));  var option4 = (res[j][i].match(/thing4-/));  var item;                             if (option1 != null)                                item = "the_thing-1";                             else    if (option2 != null)                                  item = "the_thing-2";                             else       if (option3 != null)                                 item= "the_thing-3";                             else           if (option4 != null)                                  item = "the_thing-4"; if (currentitem!= item) { currentitem = item; myarr.push("thing"+j) } } } 

given array arr:

["item1", "dummydata1", "dummydata2", "item2", ... ] 

the easiest way find set of members of form itemc, c constant mark placeholder array @ appropriate indices:

var getuniquesetofitems = function (arr) {     // our placeholder array     var p = [];     // loop through every element in `arr`     (var = 0; < arr.length; i++) {         // if first 4 characters of `arr[i]` "item"         if (arr[i].slice(0,4) == "item")             // set our placeholder array @ index true             p[i] = true;     }     // filter placeholder array indices marked true     // map filtered array indices     return p.filter(function (d) { return d; }).map(function (d, i) { return i; }); } 

this solution has benefit of having o(n) time complexity o(n) additional space. other easiest solution can think of (looping through array check whether next element there) slower, @ o(n^2).


Comments

Popular posts from this blog

css - SVG using textPath a symbol not rendering in Firefox -

Java 8 + Maven Javadoc plugin: Error fetching URL -

node.js - How to abort query on demand using Neo4j drivers -