JavaScript halt pushing when a distinct value is encountered

In this coding challenge, I am attempting to populate a 2D array using a while loop. However, I want the loop to stop pushing values into the array when the first column contains three different unique values.

The initial code looks like this:

var maxunique;
var i = 0;

while (countunique(arr) != maxunique) {

    // code that adds data to the array
    arr[i].push(RandomNumber(1,8));
    arr[i].push(i+1);
i++;
}


function countunique(arr)
{
    // function implementation here
}

function RandomNumber(min,max)
{
    return Math.floor(Math.random()*(max-min+1)+min);
}

This code currently returns the following array:

arr:  [ [ 4, 1 ],
  [ 7, 2 ],
  [ 5, 3 ],
  [ 5, 4 ],
  [ 3, 5 ],
  [ 1, 6 ],
  [ 7, 7 ],
  [ 8, 8 ],
  [ 5, 9 ],
  [ 5, 10 ] ]

The desired result should be:

arr:  [ [ 4, 1 ],
  [ 7, 2 ],
  [ 5, 3 ] ]

In this case, the process stops after the third pair is added to the array, as it already contains three unique values in the first column.

I am unsure of how to modify the code to achieve this and whether a while or for loop would be more appropriate. Any suggestions?

Answer №1

Within the iteration process used to populate the 2D array, implement a mechanism that directs the array to a validation function ensuring the presence of three unique elements as the initial components within each individual sub-array. Below is the snippet containing the validation function which evaluates and returns true until it detects the existence of three distinct elements, upon which it returns false.

var a = []; //; 
var i = 0;
while (check(a)) {
  a[i]=[];
  a[i].push(RandomNumber(1, 42));
  a[i].push(i + 1);
  i++;
}

function RandomNumber(min, max) {
  return Math.floor(Math.random() * (max - min + 1) + min);
}

function check(arr) {
  var length = arr.length;
  var tmp = [];
  for (var j = 0; j < length; j++) {
    if (tmp.indexOf(arr[j][0]) === -1) {
      tmp.push(arr[j][0]);
    }
    if (tmp.length === 3) {
      return false;
    }
  }
  return true;
}
console.log('test: ', a);
console.log('check: ', check(a));

Answer №2

To efficiently store and check the occurrence of each first number, you can utilize an object in JavaScript. In each iteration of a while loop, generate a random number for the first number and store it as a property in an object. Check if any value in this object equals 3 to break out of the loop.

var ar = [];
var obj = {}

while (true) {
  var firstNum = parseInt(Math.random() * 5) + 1;

  ar.push([firstNum, 1]);
  obj[firstNum] = (obj[firstNum] || 0) + 1;

  var stop = Object.keys(obj).find(function(e) {
    return obj[e] == 3;
  });
  if (stop) break;
}

console.log(obj);
console.log(ar);

Answer №3

One way to approach this problem is by creating a function that tracks the occurrence of numbers in the first column, incrementing a counter whenever a unique number is encountered. If the counter reaches 3, the algorithm stops pushing elements into an array and exits the loop.

Below is a sample implementation:

var data = ['-15, 1', '-15, 2', '2, 3', '2, 4', '2, 5', '77, 6', '22, 3'];

function findUnique(array) {
    var result = [], x, y, obj = {}, count = 0;

    for (let i = 0; i < array.length; i++) {
        let pair = array[i].split(',');
        x = parseInt(pair[0]);
        y = parseInt(pari[1]);

        if (count === 3) {
            break;
        }

        result.push([x, y]);

        if (!obj[x]) {
            obj[x] = 1;
            count++;
        }
    }
}

Answer №4

This code demonstrates a unique push function:

let customArray={
   arr:[],
   push:function(obj){
     for(let a=0;a<this.obj.length){
     let count=0;
       for(let i=0;i<this.arr.length;i++){
          if(obj[a]!=this.arr[i][a]){
             count++;
             if(count==3){
                break;
             }
          }
        }
      }
     this.arr.push(obj);      
    };
 };

Now you can execute the following to push an array into customArray:

customArray.push([0,1,2]);

You can retrieve it using:

alert(customArray.arr);

However, direct access to customArray is no longer possible

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

Ways to prevent the need for multiple if/else statements and repetitious function instances

Check out this code snippet in Javascript: https://pastebin.com/zgJdYhzN. The purpose of the code is to fade in text when scrolling reaches a specific point. While it does work, I want to optimize it for multiple pages without creating separate instances ...

Vanilla JavaScript: Enabling Video Autoplay within a Modal

Can anyone provide a solution in vanilla JavaScript to make a video autoplay within a popup modal? Is this even achievable? I have already included the autoplay element in the iframe (I believe it is standard in the embedded link from YouTube), but I stil ...

The Typescript compiler is throwing an error in a JavaScript file, stating that "type aliases can only be used in a .ts file."

After transitioning a react js project to react js with typescript, I made sure to move all the code to the typescript react app and added types for every necessary library. In this process, I encountered an issue with a file called HeatLayer.js, which is ...

Analyzing elements within an array of objects

Here is an array of objects I have: const cart = [ { group: "group 1", qtd: 12, value: 65, term: 20 }, //index 0 { group: "group 1", qtd: 10, value: 100, term: 20 }, //index 1 { group: "group 1", qtd: 18, value: 40, term ...

Implementing ESM in your next.config.js file is critical for optimizing

Currently, I am in the process of optimizing a Next.js project and came across the requirement to include type: 'module' in thepackage.json file. However, this led to an error being thrown: Error [ERR_REQUIRE_ESM]: Must use import to load ES Mo ...

Sending an array to unmanaged code and receiving it back without the need for duplication

Currently, I am working on creating a C# wrapper for my C++ library, and I am facing a challenge with passing arrays to unmanaged code and reading the results back in .NET. My goal is to have a wrapper function that can take an array of floats as input (m ...

The downfall of a promise leading to another promise

There are two REST calls: The first one is: http://localhost:8080/sample/rest/ser/out/2 Which returns: {"num":"2"} The second REST call is: http://localhost:8080/sample/rest/ser/person/list2/two Which returns: [{"personName":"Rahul Shivsharan","per ...

Create a web page utilizing the React library

After creating a function that is working well, I encountered an issue when trying to implement the following code: const successPage = () => { firebase.auth().onAuthStateChanged((user) => { if(user) { console.log("calling su ...

Enriching JSON Data with Additional Values

Imagine having a JSON data set structured like this: { "fruits": { "apple": { "color": red, "size": small } "orange": { "color": orange, "size": small } } Is there a way to dynamically add a name attribute ...

Is there a way to update specific content within a view in express.js without having to re-render the entire view?

I'm in the process of creating a calendar that allows users to click on dates, triggering a popup window displaying events for that specific date. The challenge lies in not knowing which date the user will click on prior to rendering, making it diffic ...

I am puzzled as to why array elements at indexes 0 and 1 suddenly turned into null values

import java.util.Scanner; public class NoteIt { public static void main(String[]args) { Scanner s = new Scanner(System.in); int Answer; int i=2; System.out.print("\nPlease Enter your Name: "); String Name = s.ne ...

Error retrieving resource: server returned a 404 status code indicating file not found for javaScript and CSS files

I can't seem to get my css and js files to load on the server. Here is how my file structure looks like: GAME_Folder https://i.sstatic.net/wzfB3.png HTML doctype html head link(href='https://fonts.googleapis.com/css2?family=Press+Start+2P& ...

Formulate a jQuery array consisting of droppable components

I have successfully implemented draggable li-elements and droppable boxes using jQuery UI. Here is my structure: A list of 3 different permission types <ul> <li data-action="create">Create</li> <li data-action="edit">Edi ...

Using WEBGL to Showcase Your Images: A Step-by-Step Guide

I'm hoping to effortlessly showcase an image on the canvas at specific x and y co-ordinates using WEBGL, but I'm unsure of the process. Must shaders be included along with all other technical details? I've come across code snippets for displ ...

What is the process for determining the date that is 28 days past a specified date?

I need assistance with finding the 28th day from a date formatted as YYYY-MM-DD. I've attempted various methods without success. Ideally, I would prefer a solution that does not involve Moment.js. Check out my code on Jsfiddle If there are no altern ...

Viewing CSV Headers with PapaParse Plugin

I am currently utilizing the PapaParse plugin to handle CSV files. I have implemented a function that generates a table for displaying the results extracted from the CSV file. function processFile(evt) { var document = evt.target.files[0]; Papa.parse(doc ...

Dynamically assigning values to class properties in Angular with Typescript is a powerful

I am working on a project where I have a class and a JSON object. My goal is to update the properties in the class based on the values in the JSON object, using Angular 9. This is the class: export class Searchdata{ name:boolean=false; age:boolean=fa ...

What is the process for running .js files on my browser from my local machine?

Hi there! I'm trying to figure out how I can create a JavaScript game in TextMate on my Mac. I want to have a regular .js file, then open it and run it in Chrome so that whatever I have coded - for example, "Hello World!" - will display in the browser ...

Find the index of a Java ArrayList regardless of its order, even if it contains nested ArrayLists

I am working with nested ArrayLists in Java. ArrayList<ArrayList<Integer>> arrays = new ArrayList<ArrayList<Integer>>(); My goal is to find the index of a similar list within this structure using the arrays.indexOf() method. While ...

Different Line Thickness in Dropdown Menu

Is there a way to adjust line heights in CSS within a drop down menu? I have attempted to change the font sizes of each element, but the new font size does not seem to take effect once an option is selected. Any suggestions would be greatly appreciated! & ...