Tips on improving the efficiency of a nested 'for' loop through functional programming

Looking for a way to optimize my function that checks for repeated cell phone numbers in a list. Currently, I am using nested for loops and wondering how I can implement functional programming instead?

  checkDuplicate(): boolean {

    for (let i = 0; i < this.phoneList.length; i++) {
      for (let j = 0; j < this.phoneList.length; j++) {
        if (i != j) {
            if (this.phoneList[i].number === this.phoneList[j].number) {
              this.toastrService.error('Phone already in List!');
              return true;
            }
        }
      }
    }

    return false;
  }

Answer №1

To identify duplicate numbers, create a Set that contains only unique numbers and then compare its length to the original array

checkForDuplicates(): boolean {
  return new Set(this.phoneNumberList.map(num => num)).size < this.phoneNumberList.length
}

Answer №2

O(n) solution

Although it's not a functional approach, this solution is currently the fastest.

const checkDuplicate = (phones)=> {
    let counts = {};
    
    for(let phone of phones) {
        if(counts[phone.number]) return true;
        counts[phone.number] = 1;
    }

    return false;
}

if(checkDuplicate(this.phoneList)) {
  this.toastrService.error('Phone already in List!');
}

Answer №3

Instead of using the filter method, consider utilizing the Set data structure for a cleaner solution. While there are multiple ways to implement this, the use of .filter() may be seen as more 'functional' due to it being a Higher-Order Component.

let exampleArray = [1,2,1,3,3,5]
let uniqueValues = [...new Set(exampleArray)]

// => [1, 2, 3, 5]

Check out the Mozilla documentation on Sets for more information.

Answer №4

One way to approach this is by using the following code snippet:

let duplicates = this.phoneList.filter(item =>
    this.phoneList.filter(item2 => item.number == item2.number).length > 1
);
if (duplicates.length) {
    this.toastrService.error('Phone number already exists in the list!');
    return true;
}

However, it may not be the most readable solution.

Answer №5

Instead of focusing on Angular, this discussion revolves around JavaScript optimization. One way to improve performance is by short-circuiting the loop within the list for faster execution.

The inner loops can be made n-i faster in processing since we have already checked those elements.

var xObj = {
  // phoneList and phoneList2 objects containing contact information
  toastrService: {
    error: function(message) {
      console.log(message);
    }
  },
  checkDuplicate: function() {
    let hasDupe = false;
    for (let i = 0; i < this.phoneList.length; i++) {
      for (let j = i + 1; j < this.phoneList.length; j++) {
        if (this.phoneList[i].number === this.phoneList[j].number) {
          hasDupe = true;
          break;
        }
      }
      if (hasDupe) break;
    }
    if (hasDupe) this.toastrService.error('Phone already in List!');
    return hasDupe;
  },
  checkDuplicate2: function() {
    let hasDupe = false;
    for (let i = 0; i < this.phoneList2.length; i++) {
      for (let j = i + 1; j < this.phoneList2.length; j++) {
        if (this.phoneList2[i].number === this.phoneList2[j].number) {
          hasDupe = true;
          break;
        }
      }
      if (hasDupe) break;
    }
    if (hasDupe) this.toastrService.error('Phone already in List!');
    return hasDupe;
  }
};
let cdup = xObj.checkDuplicate();
let cdup2 = xObj.checkDuplicate2();

console.log("Duplicates found:", cdup, cdup2);

Answer №6

Utilize the Array.some method to verify if a phone number is a duplicate, as demonstrated below. Within the loop's callback function, the phone number serves as the key for a boolean value that gets added to the exists object. The loop terminates when the callback function returns true, indicating discovery of a key/value pair matching the current item in the loop within exists.

checkDuplicate(): boolean {
  let exists: { [key: number]: boolean } = {};
  return this.phoneList.some(phoneListItem => {
    if (exists[phoneListItem.number]) {
      return true;
    } else {
      exists[phoneListItem.number] = true;
      return false;
    }
  });
}

For a demonstration, refer to this stackblitz.

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

Concealing a form after submission using JavaScript

After submitting the form, I am attempting to hide it and display a loading GIF. I've experimented with various methods, including changing ClassName to Id, but haven't had success. This is for a school project, and I've spent a significant ...

Resolving the Challenge of Disabling typescript-eslint/typedef in Angular 13 with ESlint

I started a fresh project in Angular 13 and configured typescript-eslint by running the command below: ng add @angular-eslint/schematic I made changes to my .eslintrc.json file where I disabled the rules for "typescript-eslint/typedef" and "typescript-esl ...

Attempting to save the result of a fetch call into a variable for the purpose of rendering it as a list in a

I'm attempting to fetch the top 5 NFT collections based on volume and display them in a table format. However, I'm facing an issue where the data is not being mapped correctly and when I click the "get" button, all content on the webpage disappea ...

Is there a way to verify the presence of months in a column related to departments?

Is there a way to validate whether the current row aligns with the current column month and year? If not, can it be set to 0. Let's consider the current dataset. Presenting my resultData https://pastebin.com/GHY2azzF I want to verify if this data ...

Is there a Joomla extension available that can display or conceal content upon clicking?

Looking to enhance my Joomla site by installing a plugin that allows me to toggle the visibility of content with a click, similar to how FAQ sections work on many websites. Question 1 (click here for the answer) { Details for question 1 go here } Questi ...

"Encountering problem when configuring DataSourcePaginator as the primary Paginator component in Angular

I'm currently working on setting up a table with materials but I've run into an issue while trying to implement pagination. Specifically, in the AfterViewInit stage, I encountered errors when assigning this.dataSource.paginator = this.paginator; ...

What is the best way to determine if this specific radio button has been selected?

I have been searching for solutions on stackoverflow, but haven't found anything helpful :( Currently, I am facing an issue with my HTML table that is loaded through an ajax request: <table class="table table-striped table-hover choix_annonce_tab ...

Error in Angular5 httpClient GET request: Unable to access the 'toLowerCase' property because it is undefined

When attempting to retrieve a list of Users from an API, I encountered the following error: TypeError: Cannot read property 'toLowerCase' of undefined at HttpXsrfInterceptor.intercept (http.js:2482) at HttpInterceptorHandler.handle (http.js:1796 ...

Having difficulty in loading Socket.io client .js file?

I am currently facing an issue deploying a socket.io chat on Heroku. While the page loads successfully, the client's socket.io js file is not being downloaded, resulting in the chat functionality not working. Attached are images showcasing the error ...

What is the correct way to understand nested and intricate types in Typescript?

There seems to be an issue with Typescript not properly inferring complex and nested types at times. I'm trying to figure out if this is a bug or if there's a mistake on my end. And if it's a mistake on my end, what is the most effective wa ...

Integrating a sleek Bootstrap 5 search bar drop-down functionality

As a newcomer, I could use some assistance with creating a dropdown menu that includes a search bar. Specifically, I want users to be able to select items from a list of foods or search for them. Unfortunately, I haven't been able to find a bootstrap ...

Minimum requirement for browsers such as IE9 and other compatible versions

My web app requires IE9 - what are the equivalent browser versions for Firefox, Chrome, Opera, and others? I am able to detect the user's current browser and version, and if it is not compatible, I am considering providing links for them to download ...

Utilizing the .finally method on a promise that is already being handled with try/catch statements elsewhere may lead to an UnhandledPromiseRejection

Recently, I've come across an unexpected behavior while working with nodejs. To illustrate this strange occurrence, let's consider the following example: Imagine we have two functions, foo and bar. The foo function creates a promise, attaches a ...

How can I use Java script to find specific text within table rows on a website?

I am looking to create a dynamic table that filters rows based on user input in an input text box. Here is an example table: Row 1: Apples Row 2: Oranges Row 3: Bananas When a user starts typing in the text box, I want the rows to filter accordingly. ...

Using jQuery to include a sub-object in the "data" object for each AJAX request made on the webpage

Is there a way to enhance the functionality of jQuery.ajax by including a static sub-data object in every ajax request automatically? For instance, for an ajax request like this: jQuery.ajax({ url: 'request_file.php', data: { da ...

What causes the error message "Why does Angular 10 display the error 'Cannot set properties of undefined...'" to pop up?

I'm currently developing an application that allows users to sign up by providing information such as their name, nickname, password, and type of identification. Here is the user model: export class User{ id: string; name: string; nicknam ...

Tips for correctly loading all elements on an HTML page before making CSS modifications

This question has been asked several times in the past. I am asking because when I used the on ready callback in jQuery, it did not change the placeholder text of my element "search_input". $( document ).ready(function() { $("#search_input").attr(' ...

Tips for selecting array [0] and turning it into a clickable link with JavaScript

My challenge lies in redirecting to a different URL when the user clicks on <a href="javascript:void(0)">Hotel Selection</a>. Below is my current progress. Grateful for any assistance! <div id="menu"> <ul> <li class= ...

Unable to show the total number of rows in a table depending on the selection from a drop-down menu or input field

Currently, I have a table with a variable number of rows, but it is set to display 10 rows in each page by default since the table is paginated. Now, I am working on adding a text box where users can input the number of rows they would like displayed on e ...

WebRTC error encountered: Unable to add ICE candidate to 'RTCPeerConnection'

Encountering a specific error in the browser console while working on a project involving p2p video chat. The error message is Error: Failed to execute 'addIceCandidate' on 'RTCPeerConnection': The ICE candidate could not be added.. Int ...