Evaluating the values of one array in comparison to those of another array

Exploring arrays and comparing their values. Here is an example of an array with values:

arr1 = [1,5,6,7,3,8,12];

Now we have another array that we want to compare with:

arr2 = [3,5,7];

We need to check if all the values in arr2 are present in arr1.

function containsValue(n){
  for(var i=0; i<this.length; i++){
         if(this[i] == n)
             return true;
  }
  return false;
}

arr1.containsValue("12"); //would work
// How can we efficiently check if arr1 contains all values in arr2?

The current code works for individual numbers, but how can we modify it to handle arrays and efficiently compare them?

Answer №1

  1. Make sure to expand your array so that you can utilize the function.
  2. When referencing this.length, it pertains to the function and not the array itself.

Feel free to test out the following code.

Array.prototype.equals = function (array, strict) {
    if (!array)
        return false;

    if (arguments.length == 1)
        strict = true;

    if (this.length != array.length)
        return false;

    for (var i = 0; i < this.length; i++) {
        if (this[i] instanceof Array && array[i] instanceof Array) {
            if (!this[i].equals(array[i], strict))
                return false;
        }
        else if (strict && this[i] != array[i]) {
            return false;
        }
        else if (!strict) {
            return this.sort().equals(array.sort(), true);
        }
    }
    return true;
}



var arr1 = [1, 2, 3, 4];
var arr2 = [2, 1, 4, 3];  // Loosely equal to 1
var arr3 = [2, 2, 3, 4];  // Not equal to 1
var arr4 = [1, 2, 3, 4];  // Strictly equal to 1

arr1.equals(arr2);         // false
arr1.equals(arr2, false);  // true
arr1.equals(arr3);         // false
arr1.equals(arr3, false);  // false
arr1.equals(arr4);         // true
arr1.equals(arr4, false);  // true

I trust this information proves beneficial.

Answer №2

It seems like your function contains is part of Array.prototype since you are using this.

In this case, you can simply utilize .every() to loop through and check every value in array b.

function contains(n){
  for(var i=0; i<this.length; i++){
         if(this[i] == n)
             return true;
  }
  return false;
}

Array.prototype.contains = contains;

var a = [1,5,6,7,3,8,12];

var b = [3,5,7];

var has_all = b.every(function(val) {
    return a.contains(val);
});

alert(has_all);

The .every() method will stop at the first non-matching value and return true only if all values are found.


ECMScript 5 provides an .indexOf() method, which can be used instead of defining a separate function.

var a = [1,5,6,7,3,8,12];

var b = [3,5,7];

var has_all = b.every(function(val) {
    return a.indexOf(val) !== -1;
});

alert(has_all);

Answer №3

Utilize the prototype property to efficiently reuse a function whenever it is required.

Array.prototype.contains = function (n) {
  var s;
    for(s in this){
      if (this.hasOwnProperty(s) && n.indexOf(this[s]) !== -1) {
        return true;
      }
    }
  return false;
};

var numbers1 = [1, 5, 6, 7, 3, 8, 12],
  numbers2 = [1, 2, 11];
console.log(numbers1.contains(numbers2));

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

Distributing Back-end Information to a JavaScript File

Recently, I developed a blog site from scratch that includes features such as posts, users, and comments. To build this site, I utilized MongoDB, NodeJS, and Express while implementing an EJS view. However, I encountered an issue when attempting to create ...

Stop the window from scrolling downwards

My website has a full-width slider as the main background and I am using jQuery to show or hide divs depending on the clicked link. However, when some sections are longer than the initial view, my page automatically scrolls to the bottom after a click. How ...

When the JS function 'postMessage()' is invoked on an HTML object tag, what specific action does it perform?

Not too long ago, I found myself on a quest to figure out how to trigger the print function on a PDF that I was displaying in Adobe AIR. With a bit of guidance from a helpful individual and by utilizing postMessage, I successfully tackled this issue: // H ...

Issue with JQuery delay functionality not activating correctly upon clicking an <a> tag

When I click on an <a> tag, I want to display a div and wait for 10 seconds before redirecting. However, the div is currently being shown immediately without waiting. Here is the HTML code: <a class="clickHereToDisplay" href="http://www.google.c ...

Moving from ngRoute to ui-router in AngularJS is causing a [$injector:unpr] error to be thrown

After switching the routing in my app from ngRoute to ui-router, I encountered two errors: SyntaxError: Unexpected string Uncaught Error: [$injector:unpr] Here is the updated config.route.js: (function () { var app = angular.module('app'); ...

Having trouble triggering a click event on Ant Design menu button using jest and enzyme

Troubleshooting the simulation of a click event on the Menu component using Antd v4.3.1 Component: import React from 'react' import PropTypes from 'prop-types' import { Menu } from 'antd' import { SMALL_ICONS, PATHS } fro ...

When an AJAX request is successful in Angular, utilize the ng-hide directive

I've implemented a feature where double-clicking the name displays an input field, but I'm facing an issue with switching back after a successful put-request. Despite setting $scope.edit to false, it doesn't seem to work as expected. This is ...

hiding form fields using javascript

As a beginner in javascript, I am facing a challenge with a set of checkboxes in an HTML form. These checkboxes are generated dynamically from a python script. Among them, there is a checkbox labeled "N/A" that I want to hide automatically when any other c ...

Leveraging Components within Components in Vue 2

Here is the code snippet I am working with: import './menu-item'; import ItemImage from "./item-image"; Vue.component('quest-card', { props: { title: String, isFree: Boolean, points: Number, ...

How can I resolve the issue of neglecting the result of `inputstream.read` in IntelliJ?

Currently, I am in the process of resolving potential bugs within my application. To evaluate my code, I have decided to utilize Sonar. However, I have encountered an issue that has left me puzzled: private Cipher readKey(InputStream re) throws Exception ...

Issue arises in Vue.js component array misalignment upon substituting with a smaller array

My journey with Vue.js (version 2.5.16) has just begun, but I've encountered a puzzling issue related to Reactivity: I have two sets of components displayed using v-for, which mostly render correctly - I can interact with them and even add new ones. ...

Retrieving selections from a group of checkboxes and managing their addition or removal in an array

Currently, I am in the process of creating a form that includes a group of checkboxes. My goal is to be able to capture the value of a specific checkbox when it is clicked and add it to an Array using the useState hook. If the checkbox is unchecked, I wan ...

Utilize Optional Chaining for verifying null or undefined values

I have utilized the following code: data?.response[0]?.Transaction[0]?.UID; In this scenario, the Transaction key is not present, resulting in the error message: ERROR TypeError: Cannot read properties of undefined (reading '0') Instead of chec ...

Controlling Fabric in Three.JS

(I'm still learning so forgive me if this is a beginner question.) I'm currently working on fitting a cloth material to a character model in Three.JS. What would be the most effective approach for this? Should I create a complete garment as cloth ...

Simple method to modify the text size of the entire HTML page

Looking for a way to adjust the font size of an entire HTML document? I'd like to have two buttons - one to increase the font size and the other to decrease it. Each button will trigger a JavaScript function; function increaseFontSize(){ //Increase ...

The Vue design is not being reflected as expected

Encountering a peculiar issue where the style in my Vue component is not being compiled and applied alongside the template and script. Here's the code snippet: To achieve an animated slide fade effect on hidden text upon clicking a button, I've ...

Move the div containing an <audio></audio> tag

Is it possible to drag a div with a width of 200px and an element into a droppable area, and once the div is dropped, have its size change according to the sound duration (e.g. 1px per second)? Check out this example on jsFiddle. Below is the code snipp ...

Is it possible for React Server Side rendering to be re-rendered on the client side?

In this demonstration of isomorphic rendering found at https://github.com/DavidWells/isomorphic-react-example, the author showcases Server Side Rendering by disabling Javascript. However, if JavaScript is enabled on the frontend, does it trigger a re-rende ...

Checking that an object's keys are all present in an array in TypeScript should be a top priority

I am working with a const object that is used to simulate enums. My goal is to extract the keys from this object and store them in an array. I want TypeScript to generate an error if any of these keys are missing from the array. // Enum definition. export ...

What is the process for using dojo to load content?

As I work on creating a single-page website with the help of dojo, I refer to tutorials that explain how to utilize dojo/request for ajax requests. The process is straightforward - simply make a request, receive HTML content, and insert it into a designate ...