Preventing duplicate index values in JavaScript loop iterations

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)
}
}
}

Answer №1

To discover all items in the array arr that are of the form ITEMc, where c is a constant, we can utilize a simple method involving a placeholder array:

var findUniqueItems = function (arr) {
    // placeholder array
    var p = [];
    
    for (var i = 0; i < arr.length; i++) {
        if (arr[i].slice(0,4) == "ITEM")
            p[i] = true;
    }
    
    return p.filter(function (d) { return d; }).map(function (d, i) { return i; });
}

This approach has an efficient time complexity of O(n) and requires only additional space of O(n). An alternative solution that involves looping through the array to check for duplicates would have a significantly slower time complexity of O(n^2).

Answer №2

Are you looking to achieve the following task:

let itemList = [],
  dataArray = ['sampledata1', 'sampledata2'],
  itemNameBase = "ITEM";


for(let index = 1; index < 8; index++) {
   let currentName = itemNameBase + index;
   // Adjust data for individual items based on their names
   if(itemList.indexOf(currentName) == -1) {
      itemList.push(currentName);
      itemList = itemList.concat(dataArray);
   }
}

console.log(itemList);

Answer №3

Give this a shot:

// To make the regex case insensitive, add "i" at the end
// Example: /^ITEM\d+$/i
var regex = /^ITEM\d+/;

var uniqueItems = {};
filteredArray = myArr.filter(function(element) {
    if(regex.test(element) && !uniqueItems.hasOwnProperty(element)) { 
        uniqueItems[element] = true;
        return true;
    }
    return false;
});

If you need to support older versions of Internet Explorer, remember that the filter function is only available from IE9 onward.

For an elegant solution for finding unique values in an array, visit Unique values in an array.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to rotate an image using AngularJS?

Hey there, I've got an image that I need help rotating. There are two buttons - left and right - that should rotate the image 45 degrees in opposite directions. I attempted to create a directive using the jquery rotate library, but it's not worki ...

The attribute 'selectionStart' is not a valid property for the type 'EventTarget'

I'm currently utilizing the selectionStart and selectionEnd properties to determine the beginning and ending points of a text selection. Check out the code here: https://codesandbox.io/s/busy-gareth-mr04o Nevertheless, I am facing difficulties in id ...

Integrate an item into the request body utilizing the $.load() function in jQuery

Currently, I am using a POST request via jQuery's $.load function to retrieve data to display in a window. This is what I am currently doing: var testObject = { thing1: 'data1', thing2: 'data2', thing3: &a ...

Input for uncomplicated changing identifier

I am looking to create types for dynamic keys that will be of type number. I have two similar types defined as follows: type UseCalculatePayments = () => { totalPayments: number; aggregate: number; condition: boolean; }; type UseCalculateCommissio ...

Ravaging a JSON array in Delphi

This piece of code is causing a memory leak. Can you suggest the correct approach to tackle this issue? JSONArrayObject := TJSONArray.Create; try JSONArrayObject := TJSONObject.ParseJSONVal ...

Choosing from a list in Angular

I'm trying to make a dropdown menu that shows options in the format "code-description", but only displays the "code" portion when an option is selected. For example, showing "A-Apple" in the dropdown, but displaying only "A" when chosen. I am able to ...

What is the best way to upload an object in React using fetch and form-data?

Currently, I am facing an issue where I need to send a file to my express app as the backend. The problem lies in the fact that my body is being sent as type application/json, but I actually want to send it as form-data so that I can later upload this file ...

Re-establishing Scroll Functionality Post Ajax Request Disruption caused by prettyLoader

I have created a jQuery infinite scroll function that follows the infinite scroll design pattern. After the ajax server call is completed, I am trying to rebind the scroll event. Although everything works fine for the first ajax call, the scroll event is ...

Is there a way to set an antd checkbox as checked even when its value is falsy within an antd formItem?

I'm currently looking to "invert" the behavior of the antd checkbox component. I am seeking to have the checkbox unchecked when the value/initialValue of the antD formItem is false. Below is my existing code: <FormItem label="Include skills list ...

Type in a letter of your choice into the textbox using vb.net

I am facing an issue with entering random letters into a textbox. Below is the code snippet: Imports Microsoft.VisualBasic Imports System.Timers Public Class Form1 Dim SlovaTimer As Timer Dim AbecedaArray() As Char = {"A", "B", "C", "Č", "Ć", "D", "Dž ...

Make sure to wait for the axios response before proceeding with the code inside the useEffect

I am currently facing the challenge of registering event listeners within my useEffect hook. Here is an example of what I am trying to achieve: useEffect(() => { const dataFromAxios = await axios.get('/axios-data&apos ...

Can you provide tips on how to realign an image in a contenteditable DIV in Internet Explorer?

When I have a div with the attribute contenteditable="true" in IE versions 7, 8, and 9, and then click a button to insert an image using the document.execCommand('insertImage') method, the image is successfully inserted. However, the inserted ima ...

Ensuring that the height of this specific div is set to 100% using

Is there a way to utilize the .height() method to fetch the height of each individual .post element and then assign it to the corresponding .left element? I have tried using this() but haven't been able to find a solution... Currently, my jQuery code ...

Unable to process login information with form method post on basic login page

Hi, I've been struggling with a simple login page issue. It works fine with Bootstrap, but I want to switch to Angular Material Design. I've been searching for the problem for about 3-4 hours and can't find anything. I suspect that the form ...

Tips for effectively exchanging information among angular services

Currently, I am in the process of refactoring a complex and extensive form that primarily operates within a controller. To streamline the process, I have started segregating related functions into separate modules or services. However, I am grappling with ...

Is it recommended to add the identical library to multiple iFrames?

Here's a quick question I have. So, my JSP page has 4 different iFrames and I've included JQuery UI libraries in it: <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" /> <script src="http://c ...

What benefits does invoking the .call() method on Observable functions offer?

I am new to Angular and finding it challenging to comprehend some code I came across in the ng-bootstrap project. You can find the source code here. The section that particularly confuses me is the ngOnInit method: ngOnInit(): void { const inputValue ...

What is the best way to distinguish between relative blocks and convert them to absolute positioning?

What is the best way to locate relative blocks and convert them to absolute position while keeping them in the same place? Is this something that can be achieved using JavaScript or jQuery, or is it simply not possible? Thank you very much. ...

Modifying the form select class when any option is chosen, with the exception of one

I have a feature that changes the class of a select input when a user selects any option. It works well, but I want the class to change back if the user selects the first option again. The first option is a placeholder without a value because I only want ...

Struggling with the lack of two-way data binding functionality in Kendo UI

Recently, I encountered a challenge with my kendo-dropdownlist component. Initially, I was fetching data from an API using the kendo-datasource and everything was working smoothly. However, as I started to implement multiple instances of the kendo-dropdown ...