Verifying if every item in an array exists within multiple arrays

I am struggling to find a solution to this problem.

Imagine there are 6 sets of colors with varying amounts of colors in each, and colors may be repeated:

['white', 'blue']
['green', 'yellow']
['black']
['yellow', 'blue', 'pink']
['orange', 'red']
['brown', 'white']

If a user enters 6 colors, such as white, blue, pink, black, orange, and yellow, how can I verify that all those colors are included in the sets and that each color can be chosen only once, assuming one color is selected from each set.

Hopefully, my query is clear.

EDIT: rephrasing the question

There are 6 sets of colors listed above, and the user must choose one color from each set. How do I confirm that the user's selection is accurate, considering that the order in which they submit the colors may not match the order of the sets.

Answer №1

If you're faced with a challenge like this, recursion might just save the day. While it may not be the most efficient method, it's definitely the simplest solution. And for small data sets like this, efficiency shouldn't be a major concern:

var checkColors = function(input, colors) {
    if (!input.length) {
        return true;
    }
    var inputColor = input.pop();
    var isColorMatch = false;
    for (var i = 0; i < colors.length; i++) {
        var color = colors[i];
        if (!color) {
            break;
        }
        if (color.indexOf(inputColor) !== -1) {
            colors.splice(i, 1);
            isColorMatch = checkColors(input, colors);
            if (!isColorMatch) {
                colors.splice(i, 0, color);
            } else {
                break;
            }
        }
    }
    if (!isColorMatch) {
        input.push(inputColor);
    }
    return isColorMatch;
};

Here's how you can use it:

var colors = [
  ['white', 'blue'],
  ['green', 'yellow'],
  ['black'],
  ['yellow', 'blue', 'pink'],
  ['orange', 'red'],
  ['brown', 'white']
];
checkColors(['white', 'blue', 'pink', 'black', 'orange', 'yellow'], colors);

Keep in mind that this function will modify both the colors and input arrays. It's important to create a copy of them each time you call checkColors.

This problem is reminiscent of pathfinding problems and the solution provided here is a brute force approach.

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

The PHP script receives an empty string value passed from JavaScript

I am struggling to pass a string from my JavaScript code to my PHP code. Here is the code snippet that triggers when I hit Enter in a text input: $('#user').keypress(function(e) { if(e.which == 13) { var val = $(this).val(); ...

Select component with nested checkboxes for multilevel dropdown

I am interested in developing nested dropdowns with checkboxes, similar to the example shown in this image: Image 1 Is there a way to achieve this functionality using React? I have not been able to find any specific library that allows for this implement ...

Utilizing Express.js for reverse proxying a variety of web applications and their associated assets

I am looking to enable an authenticated client in Express to access other web applications running on the server but on different ports. For instance, I have express running on http://myDomain and another application running on port 9000. My goal is to re ...

Failed to retrieve the item stored in the local storage

I am encountering an issue where I am unable to retrieve an item from local storage and display it. In store.js, I am trying to get the shippingAddress from local storage but it is not showing up in the form. Although I am able to set the shippingAddress i ...

Disable video playback on Internet Explorer 7 (with Rob W's method)

I've successfully implemented this script created by Rob W from StackOverflow, but unfortunately it's not working on IE7. You can view the script on this jsfiddle page. I've also tried importing this to enable JSON on IE, but the issue pers ...

Checking for the Existence of a Class Element within a String using JavaScript

Within my web project, there is a scenario where if a user has been logged out in one browser tab, they will automatically be redirected to the login page in any other browser tab after interacting with that page (such as clicking on a link). However, this ...

Guide to summing the values in an input box with TypeScript

https://i.stack.imgur.com/ezzVQ.png I am trying to calculate the total value of apple, orange, and mango and display it. Below is the code I have attempted: <div class="row col-12 " ngModelGroup="cntMap"> <div class="form-group col-6"> ...

Enhancing Performance by Optimizing Module Loading for Frontend Component Rendering in Next.js

When building a Nextjs app, it is common to use the same package across multiple components on a page. However, in the case of client-side rendering, the default behavior does not optimize the loading of the common package. This can result in a significant ...

When an Ajax call is made, my .html page transforms into a .php page using jQuery

The Issue While using my PHP function to send emails, everything goes smoothly. However, I'm facing an issue where I don't want the page to refresh, so I've implemented AJAX in the code below: reservation.html <form class="form-horizon ...

Trouble with Installing Express

I have encountered an issue while trying to install express, despite following various solutions without success. Upon installation, I receive the message: npm WARN <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fb8c9e9988928f9 ...

Obtaining an array from a printed array using PHP

Recently I've been working with PHP and wrote a script that outputs an array. Here's an example of how the result looks like: Array ( [0] => Array( [timestamp] => 1390242176 [length] => 32 ...

Utilizing nested JSON arrays within AngularJS for complex data structures

I'm a beginner in working with Angular and JSON, so any help would be greatly appreciated. I have a JSON array that contains information about users and the sellers from whom they have made purchases. JSON: [ { "name":"Kakaro", "sallers": ...

I am facing a challenge: I am unable to resolve the /upload error. How can

I came across this code on a tutorial video, but I encountered a "Cannot GET /upload" error. After researching on Google, it seems like the issue might be with the missing app.get('/upload') function. Unfortunately, I'm not sure how to tro ...

Converting Vue HTML to PDF without relying on html2canvas functionality

My current challenge involves creating a PDF file from either HTML or Vue component. I have experimented with various libraries such as jsPDF, html2pdf, and vue-html2pdf, but it seems like they all rely on html2canvas, causing the UI to freeze for a few ...

JavaScript Challenge: Calculate the Number of Visible Characters in a Div

I have a div with text content (a string of length S) that is fixed in size but can be of any length. When the text exceeds a certain point (referred to as L), it gets truncated, and the portion beyond that limit becomes invisible. In other words, characte ...

Using HTML and JavaScript to choose relatives from the extended family: Uncles and Aunts

Looking for a better way to target elements in your HTML code? <div class="chunk" id=""> <div class="chunkContent"> <div class="textLeft" ></div> <div class="textRight" ></div> <div class= ...

The subscription for the second Observable in RxJS concatMap is triggered individually

I am currently developing an Angular 6 application. I want the app to display a loading animation whenever there is a change in the route or if there are any pending HTTP requests. To achieve this, I have set up two Observables as follows: For httpPendingR ...

How can I implement a redirect back to the previous query page post-authentication in Next.js 13?

To enhance security, whenever a user tries to access a protected route, I plan to automatically redirect them to the login page. Once they successfully log in, they will be redirected back to the original protected route they were trying to access. When w ...

When a user clicks a button, Javascript will generate a fresh upload image form

I am interested in creating a button that, when clicked, generates a new image upload button within a form I have already created in HTML. My goal is to figure out the best approach for this functionality, especially considering that there is a remove butt ...

Property list is incomplete and requires an "after" parameter

This particular piece of code is generating the following error message: missing : after property list exactly where the error comment is placed. $("#jquery_jplayer_1-<?php echo $key.'-'.$j; ?>").jPlayer({ ready: function () { ...