I have a specific scenario in JavaScript where I need to traverse an array and check if the index matches any predefined options. If it does, I either push or print the option once. Here is the 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"]
To achieve this, I aim to loop through the array for every THING
, and if the current THING
index matches the previous one, I skip it; otherwise, I add it to the array. Although I initially tried using global variables, they did not provide the desired solution.
Expected Output:
[ITEM1 ..... ITEM7]
var currentItem ;
var myArr;
for (var j = 1; j <= 100; j++) {
for (var i = 0; i <= 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)
}
}
}