Check if a specific number appears exactly once in an array and output either True or False

I am facing a challenge with comparing two arrays

Array1 = [1,1,1,2,2,2,3,3] 
Array2 =[1,1,2,1]

When comparing both arrays, the desired result is True if the number of occurrences of Integer 1 are the same.


Array2 = [1,1,2]  //Expecting False

For the above case, the expected result is false because the occurrences of 1 and 2 in Array2 do not match with the occurrences in Array1.

Array2 = [1,1,2,3,1] //Expecting True.

I have attempted a solution but it is not effective for all instances.

function allElementsPresent(first, second) {
  return second.every((element) => first.includes(element));
}

Any help or suggestions are greatly appreciated. Thank you in advance!

Answer №1

I think I grasp the concept you're aiming to achieve. Your goal is to compare the occurrence of elements in the second array with those in the first array. To address this, I have referenced this particular answer.

function allElementsPresent(first, second, matchAll = false) {
  if (first.length > 0 && second.length === 0) return false;
  var counts1st = {};
  var counts2nd = {};

  for (var num of first) {
    counts1st[num] = counts1st[num] ? counts1st[num] + 1 : 1;
  }
  for (var num of second) {
    counts2nd[num] = counts2nd[num] ? counts2nd[num] + 1 : 1;
  }

  for (var count in counts2nd) {
    if (matchAll && (!counts1st[count] || counts1st[count] !== counts2nd[count])) return false;
    if (!matchAll && (counts1st[count] && counts1st[count] === counts2nd[count])) return true;
  }
  return matchAll ? true : false;
}

Answer №2

Here is a simple solution using JavaScript:

if (String(first).indexOf(second) !== -1 && /^[^1,]+$/.test(second)) {
    // Perform some actions
}

Dynamic types in programming can be quite helpful in simplifying tasks, especially when handling data in a generic manner. It's always good to leverage this flexibility to your advantage.

If the requirement is for the second array to have non-uniform elements (excluding only 1s), the solution becomes a bit more intricate:

if (String(first).indexOf(second) !== -1 && new RegExp('[^' + second[0] + ',]').test(second)) {
    // Perform some actions
}

This logic can also be encapsulated in a function for reusability:

function checkElementsPresence(first, second) {
    return String(first).indexOf(second) !== -1 && /^[^1,]+$/.test(second);
}

Answer №3

Make sure to first check the length of the array

if (first.length != second.length) {
  // If the number of elements is different, there is no need to proceed further
  return -1
}

Next, consider rearranging the array in a specific order using an algorithm

Then, compare each element of the arrays at the same index using two loops as shown below

for(int i =0;i<length;i++)
{
  if (first[i] != second[i]) {
    // If any elements don't match at this stage, the arrays are not equal
    return -1;
  }
}

I hope this explanation is clear

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

Looking to encode/decode a JSON response in order to transfer it to a different webpage

Currently, I have a website application where I am required to pass a JSON response (in string format) across the site. To achieve this, I have been using a hidden type value and passing it upon the submission of a link/button which subsequently triggers a ...

Failure to update the DOM after clicking a button and making an AJAX request

After experimenting with different iterations of this code, the outcomes have been mediocre and inconsistent. The concept is rather simple: A user inputs a search query into a text box, clicks a button, and the query is assigned to a var search. This varia ...

The AngularJS promise is not resolving before the external Braintree.js script finishes loading after the HTML content has been fully

Using an external braintree.js script is necessary to generate a payment widget, and unfortunately I have no control over it. The code that needs to be included in my .html page is as follows: <div id="myClient" ng-show="false">{{myClientToken}}&l ...

What is the best way to detect when a user manually changes a dropdown selection?

Is there a way to detect when a user changes a dropdown option manually, rather than when the page loads and the default value is set? I attempted using e.originalEvent, but it didn't work as expected. $(self.options.selectChange).change(function (e ...

Toggle visibility of div content when hovering over a link by leveraging the data attribute, with the div initially visible

I have a collection of links: <p><a href="#" class="floorplan initial" data-id="king"><strong>King</strong></a><br> 4 Bedrooms x 2.5 Bathrooms</p> <p><a href="#" class="floorplan" data-id="wood">< ...

Storing a collection of images simultaneously in Firebase Storage and saving their URLs in a Firestore document using Firebase v9

I am currently working on a form that requires users to input data in order to generate a detailed city document. Additionally, users must upload multiple photos of the city as part of this process. Once the form is submitted, a new city document is create ...

Can someone explain the crazy math used in three.js?

I've recently started learning three.js, and I keep encountering these complex mathematical formulas that seem confusing. Take this example for instance: mouse.set( ( event.clientX / window.innerWidth ) * 2 - 1, - ( event.clientY / window.innerHeig ...

Unknown identifier in the onClick function

I want to create a JavaScript function that can show or hide a paragraph when clicking on an arrow. The challenge I'm facing is that I have a list of titles generated in a loop on the server, and each title is accompanied by an arrow. Initially, the c ...

Acquire a JSON response from a web address by utilizing JavaScript

If you navigate to , you will find a JSON file filled with information about your current geolocation. My goal is to save this JSON data into JavaScript variables, allowing me to manipulate and extract specific fields from the file. ...

Determine whether a view is consecutive in Julia

I'm dealing with a N-dimensional julia array and a specific slice view. I want to determine if this view is contiguous, similar to a.flags["F"] in NumPy. It appears that Base.iscontiguous isn't giving me the desired result. a = ones((1, ...

Is there a way to completely clear a form using jQuery in JavaScript?

I have a functioning script that sends emails via Ajax and PHP. However, I am also looking to reset the form after sending an email. Below is my jQuery code: <script src="http://code.jquery.com/jquery-latest.js"></script> <script> $(doc ...

I'm encountering problems when attempting to display the image/png response from an xmlHTTPRequest. Instead of the correct data, I

I have implemented the following code to integrate a captcha generating web service. The response data is successfully obtained, but when I attempt to display the result within a div element, the image appears as distorted text. var xmlHttp = new XMLHtt ...

Unusual trait of TrackballControls.target within the world of Three.js

My current project involves simulating a 3D distribution of galaxies. In this simulation, the galaxies are represented as points. question1.htm references galaxydata1.txt to calculate and load the galaxy positions: rawFile.open("GET", "galaxydata1.txt", ...

Can you explain the purpose of `import type {Node} from 'react';` and how it is used in the App component as: () => Node?

Executing the following command: npx react-native init AwesomeProject When reviewing the App.js file, I came across two lines that confuse me: import React from 'react'; import type {Node} from 'react'; // Line 1 import { SafeAreaVi ...

Avoiding memory leaks when using three.js with a large number of shapes

My code is devouring memory at an alarming rate and ultimately crashing. After some investigation, I've determined that the issue seems to be related to the torus generation/removal portion of the code. Despite efforts to manage the scene array and t ...

Select2.js Dropdown List with Case Sensitivity

Currently making use of select2.js version 4.0.3 Situation: Imagine the dropdown list contains the following options: JavaScript javascript Javascript javaScript So, when a user types in java, all options are displayed (case is n ...

validating if Object may be either 'null' or 'undefined'

In the code snippet below, I am attempting to verify whether hostel.country.address is null: return hostel.country.address && hostel.country.address.internalEmployeeIdentifier !== null || hostel.country.address.exter ...

Sending JSON data back to the server using KeyValuePair in C#

My goal is to send my JSON list back to the POST method (EditCompanyReportField) on the C# server side. The related parameter (fieldSorted) in my method is an array object, but the values are not being passed through. I have a few question marks regarding ...

Using jQuery to iterate through JSON data obtained from a web service

In this code snippet, I am attempting to retrieve a JSON response from a PHP page and then iterate through it to display the name field of each JSON object. However, for some reason, nothing is being alerted out. <html> <head> <title>A ...

Ensure that clicking on an element closes any currently visible elements before opening a new element

Take a look at my code snippet below. I am working on creating multiple clickable divs that reveal different content when clicked. However, the issue I am facing is that currently, both content blocks can be displayed simultaneously. My goal is to have onl ...