The code is functional with regular arrays, however, it does not support multidimensional arrays

Currently, I am working on developing a Holdem hand evaluator which requires me to create a function that calculates the number of possible combinations of 5 cards from a selection of 7 cards. I have successfully written the "pickNofSet()" function to achieve this, however, it is producing duplicate results that need to be removed.

Therefore, I need to implement a "removeDuplicates()" function. The issue I am facing is that while this function works well with a simple array, it fails to handle the "arrays of arrays" generated by my "pickNofSet()" function.

-- Here is the code for the removeDuplicates function --

var removeDuplicates = function(input){ // takes array
var output = [];
for (i=0; i < input.length; i++){
    var unique = true; // all elements are innocent until proven guilty
    for(j=i+1; j < input.length; j++){
        if(input[j] === input[i]){
            unique = false; // guilty!
        };// endif
    };// end jfor
    if(unique){ // if not found guilty, 
        output.push(input[i]); // you may go free, little element
    };// end if
};// end ifor
console.log(output);
return output;  };//end function

Upon testing in the Console, here are the results:

> removeDuplicates(['a','b','c'],['a','b','c'],['d','e','f'],['g','h','i']);
< undefined
> removeDuplicates([1, 2, 2, 3, 3, 5, 5, 6, 6, 6]);
< [1, 2, 3, 5, 6]

Answer №1

Operator === unable to compare arrays

When you use === to compare two elements, it only works with primitive data types, not arrays. For example:

1===1 // true
[1]===[1] // Sorry, this won't work

If you need your algorithm to handle both primitive elements and arrays, you might have to switch from === to a custom function for equality check.

From this:

if(input[j] === input[i]){
   unique = false; // guilty!
};// endif

To this:

if (equals(input[j],input[i]){
   unique = false; // guilty!
};// endif

And create an equals function that can compare both primitive data types and arrays:

function equals(a,b){
    if (typeof(a)!=typeof(b))
        return false;
    else if (typeof(a)=='object'){
        if (Object.keys(a).length != Object.keys(b).length)
            return false;
        else{
            for (var keyA of Object.keys(a)){
                if (!(keyA in b))
                    return false;
                else if (a[keyA]!==b[keyA])
                    return false;
                else
                    return true;
            }
        }
    }
    else
        return a===b;
}

Hint: This solution should, hopefully, also work with JSON objects.

Answer №2

Below is a unique filter example that can be used for various purposes and should fulfill your requirements. It works best in an environment that complies with ES5 standards.

(function () {
    'use strict';

    function $strictEqual(a, b) {
        return a === b;
    }

    function $isUndefined(inputArg) {
        return $strictEqual(typeof inputArg, 'undefined');
    }

    function $isPrimitive(inputArg) {
        var type = typeof inputArg;

        return type === 'undefined' || inputArg === null || type === 'boolean' || type === 'string' || type === 'number' || type === 'symbol';
    }

    // Other filter functions here...

    if (!Object.prototype.uniqueFilter) {
        Object.defineProperty(Object.prototype, 'uniqueFilter', {
            enumerable: false,
            configurable: true,
            writable: true,
            value: function (equalFn, thisArg) {
                // Implementation of uniqueFilter function
            }
        });
    }

}());

// Example usage of the unique filter
var data1 = [1, 2, 2, 3, 3, 5, 5, 6, 6, 6],
    data2 = [
        ['a', 'b', 'c'],
        ['a', 'b', 'c'],
        ['d', 'e', 'f'],
        ['g', 'h', 'i']
    ],
    equals = Function.prototype.call.bind(Object.prototype.uniqueFilter),
    pre = document.getElementById('out');

pre.textContent = JSON.stringify(data1.uniqueFilter(equals), null, 2);
pre.textContent += '\n\n';
pre.textContent += JSON.stringify(data2.uniqueFilter(equals), null, 2);
<pre id="out"></pre>

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 the color of the TripsLayer in deck.gl

layers.push(new TripsLayer({ id: 'trips', data: trips, getPath: (d: Trip) => d.segments.map((p: Waypoint) => p.coordinates), getTimestamps: (d: Trip) => d.segments.map((p: Waypoint) => p.timestamp), ...

Having trouble with Raphael's animation callback function?

It seems like I may not be using the callback feature correctly because when I run the code below, the "testCircle" doesn't animate before it disappears. var paper = Raphael(0, 0, 1280,600); var testCircle = paper.circle(300, 300, 50); test ...

Transform JSON data into HTML format while excluding particular values

I recently integrated a JSON API that fetches event data. Here's a snippet of the JSON structure: { "id":1, "status":"ok", "start":{ "date":"2021-01-16" } } To display this ...

What method can I use to adjust the font style when it overlays an image?

Sorry if this is a bit unclear, but I'm trying to figure out how to change only a section of my font when it overlaps with an image while scrolling. If you visit this example website, you'll see what I'm referring to: For a visual represen ...

Climbing the ladder of function chains, promises are making their

Here is the code structure that I've created to upload multiple files to a server using AJAX. After all the uploads are complete, it should perform a certain action. function uploadFiles(files){ const results = [] for (let i=0; i<files.length; i ...

Error: Phonegap displaying incomplete or corrupted image

Currently, my Android application is being developed with Phonegap. Users have the ability to take photos that are then stored in a mysql database (medium-blob column) using a simple INSERT INTO query without altering the data. These images are then sent s ...

Combining two arrays of objects in JSON files based on a shared key

Seeking assistance to merge two object arrays in JavaScript/jQuery based on a common key (code). These arrays are sourced from separate JSON files. I've provided shortened versions of the files as they are lengthy. Appreciate any help in advance. O ...

Is it possible to verify the versions of node and npm prior to running an npm install command?

To ensure only specific versions of node and npm are used before a user can run the npm install command on my module, I need to set certain criteria. According to NPM documentation, I can use the engine attribute for this purpose: "engines": { "nod ...

The routeLink feature is unable to display the URL dynamically

https://i.sstatic.net/iD53V.png <table class="table"> <thead> <tr> <th>Name</th> <th>Price</th> <th></th> </tr> </thead> ...

View the picture in a web browser

Currently, I am faced with the challenge of displaying an image that is stored in an MSSQL database created by another person. The column was originally of type IMAGE, but I converted it to varbinary(MAX) using Sequelize. Although I lost some data during ...

Determining the dimensions of a div with a scrollbar using Jquery

Is there a way to get the width and height of a div with scroll that includes both visible and hidden content using JQuery? If anyone has a solution for getting these values, please share. <div id="area" class="divLeftCem area"> <div id="pan ...

Utilizing the indexOf Method in AngularJS

Here is my array: emp=["111","56"]. This is the code I have: <input type="text" placeholder="Enter" class="form-control" name="Emp" ng-model="myModel.Emp" ng-required="currentStep ==2"/> <input type="text" placeholder="Enter" class="form-contro ...

Top technique for extracting json files from post requests using nodejs

Situation: I'm running a Node.js REST server that receives JSON files, parses them, and inserts them into a database. With an anticipated influx of hundreds of requests per second. Need: The requirement is to only perform insertions by parsing the JS ...

What are the steps to integrate the vue-tweet-embed node package into vuejs2?

I am having trouble figuring out how to implement the vue-tweet-embed plugin in my Vue file. I keep getting an error message that says: Unknown custom element: - have you properly registered the component? If dealing with recursive components, ensure ...

RainTpl: accessing specific array value within loop based on key

After assigning an array for language to tpl, I also assign another array fetched from a database query. Now, I need to print the values from the language array using the keys from the query array by looping through them: $arrayLang = array ( "id" =&g ...

What is the best way to simulate a service that returns a promise when writing unit tests for AngularJS using Jasmine?

I have a service named myService that relies on another service called myOtherService. The latter makes a remote call and returns a promise. Here's the implementation: angular.module('app.myService', ['app.myOtherService']) .fac ...

Toggling the visibility of divs in a dynamic layout

How can I use JQuery/JavaScript to show only the comment form for a specific post when a button or link is clicked on a page containing multiple posts divs with hidden comment forms? <div class="post"> <p>Some Content</p> <a ...

Reading values from a properties file using HTML

Here's a snippet of my HTML code: First name: <input type = "text" > Last name: <input type = "text"> Instead of manually inputting the field values (First name, Last name) in the HTML, I am interested in reading them ...

Assigning an argument of type `any` to a parameter of type `Observable<IComboboxItem[]>` can be considered risky

I have a piece of code that retrieves data from the backend server. Here is the code snippet: @Injectable() export class DictionariesDatasourceFacadeService { public invoiceTemplate: IDataSource<IComboboxItem>; public replacedLegalEntity: IData ...

Do JavaScript functions in separate <script> tags exist in the global scope?

Here's a scenario I'm dealing with in an HTML file: <script> var my_function = function(param) { alert(param); } </script> <div> <!-- snip --> <script> $(function() { my_function("Hello wor ...