Adding value to array if it meets the criteria

Here is the code snippet I've put together

function findValueInArray(value, array) {
    var result = false;
    for (var i = 0; i < array.length; i++) {
        if (array[i] === value) {
            result = true;
        }
    }
    return result;
}

function removeDuplicates(array2) {
    var uniqueArray = [];
    for (var i = 0; i < array2.length; i++) {
        var val = array2[i];
        if (!findValueInArray(val, uniqueArray)) {
            uniqueArray.push(val);
        }
    }
    console.log(uniqueArray);
}

However, upon executing this piece of code, it results in freezing the browser. What could potentially be causing this issue?

Answer №1

It appears that you have forgotten to include the var keyword in your loops:

for(i=0;i<array.length;i++){

...

for(i = 0 ; i<array2.length; i++){

This means that all your loops are using the same global variable i. This can lead to issues, such as resetting the counter used in someFunction and causing an infinite loop.

Make sure to add the var declaration in all your loops like this:

for(var i=0; i<array.length; i++){

On a side note: you do not necessarily need to iterate over the entire array in the arrayContains function. You can simplify it like so:

function arrayContains(value, array){
    for(var i=0; i<array.length; i++){
        if(array[i]==value) return true;
    }
    return false;
}

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

Retrieve information using the request npm package

Currently, I am in the process of developing an application with express js. My approach involves using request(v-2.88.2) to retrieve data from an api. request(url, function(error, request, body) { var data = JSON.parse(body); }); My goal is to utili ...

Storing data offline within HTML documents

Is there a way to store offline data/images (20MB+) in HTML that is compatible with IE 10 Metro browser? I have looked through the resources provided in the following links: Building Offline storage I would appreciate it if you could provide me with a wo ...

Dealing with the chaos of imports in React: Tips and Tricks

Struggling with the import process in my react app when running it through Node. Any tips for simplifying this maze? Currently, I execute the following command as npm start: ./node_modules/.bin/babel-node --presets react,es2015 server/server.js This lau ...

Enter the previous script type

Uncertain about the type to assign here. "HowitterObject" in setHowitters represents data and "...prev' is the ongoing accumulation of data from howitterObject. interface IhowitterMessage { message: string; createAt: number; id: ...

Retrieve and showcase Resident information upon clicking the view button through ASP.NET Core

UserDashboard.cshtml <table class="display table" id="ManageUser" style="width:100%"> <thead> <tr> <th>User ID</th> <th>Username</th> &l ...

Using Ext JS to display content in a specific div element

I am having trouble displaying an Ext JS component within a simple div. I know it should happen through renderTo, but when I try to assign the id of the div in the Ext JS code, it doesn't work. For more details and code examples, click on the followi ...

JS stop the timer from the previous function call before starting a new function call

Within my React app, I have implemented a slider component from Material UI. Each time the slider is moved, its onChange event triggers a function to update the state. However, I have noticed that the component rerenders for every step of the slider moveme ...

Retrieve the id of the anchor tag that was selected upon clicking, and then dynamically change the content of another div

Seeking guidance on how to dynamically change the content of a div element based on which anchor tag is clicked. Below is the HTML structure and JavaScript function I have attempted: HTML: <div> <a id="a1" href="javascript: changeDiv();">tag1 ...

Having issues with $_POST not retrieving values from .post

Below is the javascript snippet that I have written: function submitForm() { var name = document.getElementsByName('name').value ,email = document.getElementsByName('email').value ,subject = document.getElementsBy ...

Retrieving data from a JSON using Typescript and Angular 2

Here is an example of what my JSON data structure looks like: { "reportSections": [ { "name": "...", "display": true, "nav": false, "reportGroups": { "reports": [ { "name": "...", "ur ...

What is the reason for jQuery selector variables not functioning within namespaces?

I'm struggling to figure out why my code isn't working as intended. I'm trying to declare multiple variables, but something seems to be off. Can anyone help me spot the mistake? var message = (function ($) { var $modalBody = $( ...

Unraveling a JSON String with Javascript

I have received an encoded JSON string with the following values, which I need to display on my webpage after retrieving them from a database. {"Value 1":"1234","Value 2":"123456"} Can someone please guide me on how to decode this string and format the d ...

"Disabling Click Event on Sidebar Menu in Angular: A Step-by-Step Guide

I am working on an Angular project with a sidebar that I want to modify in order to disable click events on the menu items. My goal is to guide users through a specific flow without allowing them to navigate freely. However, simply disabling the [routerLin ...

Challenge with jQuery UI Draggable: Div moves slower than mouse cursor

My issue is that when I move the mouse, the mouse moves faster than the div underneath it. I am using jQuery UI 1.12.1 and jQuery 3.3.1 with default options. Here is my HTML: <div class="popup"></div> And here is my jQuery code: $(function( ...

What is the best way to incorporate an apostrophe into a string so that it can be displayed in a tooltip using jQuery

There is a text or string stored inside the 'data' variable, containing some texts with apostrophes. The issue I'm facing is that the tool tip is not displaying the text after the apostrophe symbol. How can I include all texts, including apo ...

After applying styling, the modal close button refuses to be clicked

I'm currently facing an issue where I am trying to enhance a modal window with a close button, but encounter problems once styling is applied. The unique aspect of this problem arises from the fact that the close button is not directly in the page HTM ...

Event for terminating a Cordova application

We are looking for a way to send a notification to the user's device when our app is closed rather than just paused. On iOS, this occurs when you double click the home button and swipe up on the app, while on Android it happens when you press the Men ...

Shut down the elegant box using the function housed within the 'fancybox' opening

Hey everyone! I'm looking for a way to close fancyBox when it's already open. I've attempted the code below without any success: function closeFancyBox(html){ var re = /.*Element insert complete!.*/gi; if( html.search( re ) == 0 ){ ...

Obtain the CSRF token from a webpage using JavaScript

I am currently working on a project where I need to retrieve the csrf token from a web page built with Django using javascript. The structure of my HTML template is as follows: <div class = "debugging"> <p id = "csrf">{% csrf_token %}</p ...

Incorporate the key as a prop within a Child Component in a React application

I am trying to display a list of elements in React, where the key of each element is used as an index in front of the item. However, when I try to access props.key, it just returns undefined. Does anyone have any suggestions on how to access the key proper ...