Comparing the Length of JavaScript Arrays

I have code that checks for similar values in two arrays, and if there are any, they are not displayed in the result. However, when I switch the lengths of the arrays so that Array2 is longer than Array1, I end up with an empty result array. How can I achieve the same result regardless of which array is longer?

Here is my code:

var Array2 = [ "1", "2", "3", "4", "5" ]; 
var Array1 = ["1","2","3"];
      
var result = [];
      
for(var i = 0; i < Array1.length ; i++){      
  var x = Array1[i];
  var check = false;        
      
  for( var y = 0; y < Array2.length; y++){         
    if(x == Array2[y]){
      check = true;
    }
  }
  if(!check){
    result.push(x);
  }
}
console.log(result);

Answer №1

If you want to eliminate duplicates from arrays, you can utilize the ES6 .filter() method.

Using ES6:


let Array2 = [ "1", "2", "3", "4", "5" ]; 
let Array1 = ["1","2","3"];

let result = Array2.filter(val => !Array1.includes(val));

console.log(result);

Vanilla JavaScript Method:


let Array1 = ["1", "2", "3"];
let Array2 = ["1", "2", "3", "4", "5"];

function getMissing(a, b) {
  var missings = [];
  var matches = false;

  for (let i = 0; i < a.length; i++) {
    matches = false;
    for (let e = 0; e < b.length; e++) {
      if (a[i] === b[e]) matches = true;
    }
    if (!matches) missings.push(a[i]);
  }
  return missings;
}

console.log(getMissing(Array2, Array1));

jQuery Method:


let Array1 = ["1", "2", "3"];
let Array2 = ["1", "2", "3", "4", "5"];

let difference = $(Array2).not(Array1).get();

console.log(difference);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Answer №2

Here is a better way to approach the problem:

var Array2 = [ "1", "2", "3", "4", "5" ]; 
var Array1 = ["1","2","3"];

var result = [...Array1.filter(v => !Array2.includes(v)), ...Array2.filter(v => !Array1.includes(v))];
console.log(result);

To further enhance performance, consider this alternative method:

var Array2 = [ "1", "2", "3", "4", "5" ]; 
var Array1 = ["1","2","3"];

var map2 = Array2.reduce((a,c) => Object.assign(a, {[c]:true}), {});
var map1 = Array1.reduce((a,c) => Object.assign(a, {[c]:true}), {});

var result = [...Object.keys(map2).filter(k => !map1[k]), ...Object.keys(map1).filter(k => !map2[k])];
console.log(result);

Answer №3

Detailed method

var uniqueArray1 = ["apple", "banana", "orange"];
var commonArray = ["banana", "grapefruit", "orange", "kiwi"];

var resultArray = [];
var isMatch = false;

if(uniqueArray1.length >= commonArray.length){
  findUniqueValues(uniqueArray1, commonArray);
}
else{
  findUniqueValues(commonArray, uniqueArray1);
}

function findUniqueValues(mainArray, subArray){
  $.each(mainArray, function(indexMain, valueMain){
     isMatch = false;
     $.each(subArray, function(indexSub, valueSub){
           if(valueMain === valueSub){
             isMatch = true;
            }          
      });
      if(!isMatch){
        resultArray.push(valueMain);
      }
  });
}
console.log(resultArray);

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

Tips for dividing HTML code on a page into individual nodes

I am looking to extract the HTML content from a website and then parse it into nodes. I attempted the following code: function load() { $(document).ready(function () { $.get("https://example.com/index.html", function (data) { const loadpage ...

What could be causing my JavaScript loop to replace existing entries in my object?

Recently, I encountered an issue with an object being used in nodejs. Here is a snippet of the code: for(var i = 0; i < x.length; i++) { var sUser = x[i]; mUsers[sUser.userid] = CreateUser(sUser); ++mUsers.length; ...

What is the best way to confirm if a Json response is empty or not?

{"PatientPastMedicalHistoryGetResult":{"PastMedicalHistory":[]}} The PastMedicalHistory object does not contain any values. How can I verify if it is empty? ...

Mobile device scrolling glitch

I'm currently working on my website, which can be found at . After testing it on mobile devices, I came across an issue that I just can't seem to fix. For instance, when viewing the site on a device with 768px width, you can scroll to the righ ...

Change the position of a Div by clicking on a different Div using JQuery for custom movements

I have successfully managed to slide the div left/right based on the answers below, but I am encountering some issues with the top div. Here are the specific changes I am looking to make: 1. Make both brown lines thinner without affecting the animations. ...

AngularJS Error: The method serviceName.functionName() is not a valid function

I am trying to implement a function that will go back when the cancel button is clicked. Here is the view code: <div ng-controller="goodCtrl"> <button class="btn" ng-click="cancel()">Cancel</button> </div> And here is the Jav ...

Even with React.memo(), functional components continue to trigger re-renders

I am facing an issue with my button component that contains a button inside it. The button has a state isActive and a click function passed to it. Upon clicking the button, the isActive flag changes, triggering the app to fetch data accordingly. However, t ...

Save the URLs of all links into an array using PHP

I need help with extracting URLs from a HTML document and then storing them in an array using PHP. Imagine if the document's source code looks like this: Blah blah blah <a href="http://google.com">link</a> blab <a href="http://yahoo.co ...

Can express middleware be tailored for each individual handler within the same route path?

I am seeking to create distinct routes under an /api path with varying middleware handlers, each allowing for different authentication methods. My initial approach was to nest these API routes under separate instances of the Router object using Express: c ...

Utilizing the push method to add a JavaScript object to an array may not be effective in specific scenarios

When I tried using users.push within the 'db.each' function in the code below, it didn't work. However, moving the 'users.push' outside of it seemed to do the trick. Is there a way to successfully push the new objects from db.each ...

JavaScript Bridge function in WebView not invoked

I encountered a strange issue with my application, which functions as an e-reader. To invoke functions for the web view, I utilize a JavaScript class: public class MyJavaScriptInterface { Context mContext; /* Instantiate the interface ...

Query the number of Firebase instances using the firebase.appCount property in Firebase v

When setting up Firebase in my React applications, I typically initialize it as follows: if (firebase.apps.length < 1) { firebase.initializeApp(firebaseConfig); // Additional initialization for other Firebase products } This method was working flaw ...

JavaScript and HTML with Node.js

Exploring the world of HTML, running smoothly with a static IP address 192.168.56.152 using apache on the host computer. <!DOCTYPE html> <html > <head> <title>OnlinePage</title> <meta charset="utf-8"& ...

Is it possible to bypass the initial bracket when working with arrays in PHP?

I am trying to display the [number] value from each array, but with different parent brackets [], how can I skip the first one and retrieve the desired [number]? Basically, I need to ignore the first set of brackets [] and access the second one containing ...

The dojo array implemented a new element, pushing out the old one

The JavaScript code below is supposed to populate the array personNames with objects containing names from an array of persons. However, it incorrectly repeats the same name for each object instead of assigning different names: [{"name":"smith"},{"name":" ...

Activating a hyperlink within a Div element by clicking on the Div itself

In my card element, I have a link that, when clicked, opens a modal pop-up containing all the necessary project information. I am currently attempting to trigger a click event on that link whenever any part of the div is clicked. This task is for a school ...

React approach for managing multiple combobox values

Currently, I'm working on a page where users can upload multiple files and then select the file type for each file from a dropdown menu before submitting. These 'reports' are the uploaded files that are displayed in rows, allowing users to c ...

Getting rid of redundant elements in an array using Javascript or AngularJS

Case Study 1 A situation arises where an API I am using returns an array with duplicate values. var originalArray = [{id:1, value:23},{id:1, value:24},{id:1, value:22},{id:2, value:26},{id:3, value:26}]; //example Inquiry 1 -> How can I remove the du ...

Ajax call encounters 404 error but successfully executes upon manual page refresh (F5)

I am encountering a frustrating issue with my javascript portal-like application (built on JPolite) where modules are loaded using the $.ajax jquery call. However, the initial request fails with a 404 error when a user first opens their browser. The app i ...

Removing specific text from a textarea containing a vast quantity of information

I developed a simple XML formatter using HTML and Javascript. I am looking to incorporate a delete feature into it. Essentially, I want the ability to remove an entry without affecting any other data. <contact <!--Jane Smith--> first_name="Jane" ...