Generate a fresh number that stands out from the rest of the numbers in the array

I'm facing a challenge with arrays that I can't seem to resolve. My goal is to locate numbers that are not part of the array. The function should only return a value if it's not already in the array, otherwise, it should increment the value (to ensure no duplicates).

Here's how my code looks:

function create_number(number) {
  var array = [1,2,3,6,7,8,9];
  for (var i=0;i<array.length;i++) {
    if (array[i] == number) {
      return number;
    } else {
      // generate a new number that doesn't exist in the array and return it.
    }
    // If not found, repeat the loop. 
    // If no match is found after looping through, generate a valid number 
    // that is not included in the array.
  }
}

Answer №1

let numbersArray = [1,2,3,6,7,8,9];
let currentNumber = 0;
while (true) {
    if (numbersArray.indexOf(++currentNumber) == -1) {
        numbersArray.push(currentNumber);
        return currentNumber;
    }
}

Remember to store the numbersArray somewhere

PS: Check out this compatibility shim for Array.prototype.indexOf for older browsers (credits to @Lochemage)

PPS: The previous solution is O(N^2), here's a more efficient O(N) solution (assuming numbersArray is sorted initially):

let sortedArray = [1,2,3,6,7,8,9];
let num = 1;
while (true) {
    if (sortedArray[num - 1] != num) {
        sortedArray.splice(num - 1, 0, num);
        return num;
    }
    ++num;
}

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

I'm curious, are there any html rendering engines that can display text-based content using curl-php?

When utilizing PHP cURL to interact with webpages, I often find myself needing to use regular expressions if the page contains AJAX and JavaScript elements. Does anyone have any recommendations for rendering HTML pages and extracting the text-based render ...

Modifying source dynamically in Javascript file through web.config during runtime

I have the following code snippet: <script type="text/javascript" src="path?key=1234567890"> </script> Additionally, I included the following in my web.config file: <appSettings> <add key="key" value="1234567890"/> Now, ho ...

Tips on transforming a JSON file into a response for my personal server

After successfully converting an Excel file to JSON format using my code, I encountered a challenge when trying to convert this as a response. Despite attempting to use res.send in the JS code, it only displayed directory/inner codes instead of a response. ...

Loading indicator displayed at the top of a div using JavaScript/jQuery

My current challenge involves implementing a progress bar, similar to the pace.js progress bar. The issue arises when the browser is refreshed, as the pace.js progress bar loads on top of the body instead of within a specified div. It is important that the ...

Why isn't the onChange function triggering in the input type text when the input is not manually typed in?

I am currently facing an issue with two text fields in my HTML form. Here is how they are set up: HTML : <input type="text" id="input1" onchange="doSomething();" disabled/> <input type="text" id="input2"/> JavaScript : function doSomething( ...

Are you curious about the array of elements in React's carousel?

I'm currently in the process of constructing a website using React, and I have a specific challenge related to the "news" section. Within this section, I have a list of three components that represent different news items. These components are housed ...

Invoke the jquery plugin upon completion of the HTML load via Ajax

For my current project, I needed to style input radio buttons and decided to use the jquery uniform plugin. However, the radio buttons are displayed after some Ajax content is loaded onto the page. Since I do not have permission to edit the form or Ajax ...

Trouble receiving JSON data from jQuery method

I am encountering difficulty in correctly capturing a JSON object within a function that is executed when the page loads. My goal is to capture this object so that I can later POST it to another page based on user action. This code is being run on Windows ...

Retrieve information from a JSON file within a Vue.js application rather than entering data manually

I am venturing into the world of Vue.js for the first time. I have created an app that currently relies on manually added data within the script. Now, I am looking to enhance it by fetching data from a JSON file, but I'm unsure about how to proceed wi ...

What is the best way to establish a default search query within the vue-multiselect component?

I have incorporated vue-multiselect into my project. You can find more information about it here. This is a snippet of my template structure: <multiselect v-model="value" :options="options" searchable="true"></multiselect> When I open the mu ...

eslint rule prohibiting directly checking numbers

Does eslint have a rule that flags an error for the code snippet below: function parseNumber(numberToCheck: number | undefined) { // I want an error here: !0 is true, so we will get "no number" here if (!numberToCheck) { return "no n ...

Optimally displaying extensive lists on a webpage using HTML

Are there any advanced javascript libraries that can efficiently handle loading a large list by only loading the visible part and simulating the scrollbar? <div id='container'> <!-- Empty space to mimic scrollbar, but preloading conte ...

I constantly encounter the error message "Unable to access properties of undefined (reading 'map')"

I am in the process of using Nextjs 13 for developing my front end and I have a requirement to fetch a .json file from a URL and utilize it to populate my website through server side rendering. However, I keep encountering an error saying "Cannot read prop ...

The function array.filter is returning the complete object rather than a single value

I'm facing an issue with a function that filters an array. My goal is to retrieve only the string value, not the entire object. However, I keep getting back the entire object instead of just the string. Interestingly, when I switch the return state ...

Exploring the potential of jQuery and AJAX for dynamic content generation:

I have developed a jQuery plugin that pulls data from a JSON feed (specifically YouTube) and then presents the results in a DIV. Everything is working well until I need to display the results with different configurations, such as more videos or from anoth ...

Vue fails to detect changes in an Array

Hey everyone, I'm currently working on a Vue project and I have been attempting to create a recursive tree from a flat list. My goal is to toggle the expanded property of each item when clicked, but for some reason, it's not updating. The issue ...

Material UI: Easily adjusting font size within Lists

When developing forms with react js and material UI, I encountered an issue with changing the font size within lists to achieve a more compact layout. The code fontSize={10} didn't seem to have any effect regardless of where I added it. Is there a wa ...

What is the best way to eliminate a specific group of characters from a collection of strings in Javascript or AngularJS while avoiding duplicating them?

Imagine I have an array like this: $scope.array = ["ABC", "ABCDEF", "ABCDEFGHI", "ABCAFGKJA"]; Is there a way to transform it into the following format? $scope.array = ["ABC", "DEF", "GHI", "KJ"]; Apologies if my question is unclear, I'm still get ...

Mistake in algorithm for identifying peaks

Hey everyone, I could really use some assistance with my code. My code is for peak finding. In case you're not familiar with the concept of peak finding, here's a quick explanation: Peak finding involves finding a peak element in an array of in ...

What could be causing React onclick events to not trigger when wrapped within a Vue application? (No additional libraries)

As I dive into the world of combining React and Vue components, I encountered an interesting challenge... const RootTemplate = () => { return ( <div id="vue-app"> ... <IconButton color="inherit" onClick={thi ...