Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
Difference between Array and Array of Objects in JavaScript
Next article icon

Difference Between Two Arrays in JavaScript?

Last Updated : 12 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

These are the following ways to Get the Difference Between Two Arrays in JavaScript:

1. Using the filter() and includes() Methods - Mostly Used

We can use the filter() method on the first array and check if each item is not present in the second array using the includes() method. The resulting array contains the elements that are present in the first array but not in the second array.

JavaScript
let a1 = [1, 2, 3, 4, 5]; let a2 = [3, 4, 5, 6, 7];  let res = a1.filter((e) => !a2.includes(e));  console.log(res);  

Output
[ 1, 2 ] 

2. Using for Loop and indexOf() Method

To find the difference between two arrays in JavaScript, you can iterate over one array using a for loop and check if each element exists in the other array using the indexOf() method. If an element is not found, it is added to the result array.

JavaScript
let a1 = [1, 2, 3, 4, 5, 0]; let a2 = [3, 4, 5, 6, 7, 9]; let res = [];  for (let i = 0; i < a1.length; i++) {     if (a2.indexOf(a1[i]) === -1) {         res.push(a1[i]);     } } console.log(res); 

Output
[ 1, 2, 0 ] 

3. Using Set and filter() Method

The arrays are converted to Sets using the Set constructor. The Set data structure only allows unique values. By filtering out the elements from the first set that also exist in the second Set, we can obtain the difference.

JavaScript
let a1 = [1, 2, 3, 4, 5]; let a2 = [3, 4, 5, 6, 7];  let s1 = new Set(a1); let s2 = new Set(a2);  let res = [...s1].filter(     (e) => !s2.has(e));  console.log(res); 

Output
[ 1, 2 ] 

4. Using reduce() and includes() Methods

This method iterates over the first array and checks if each element is present in the second array using the includes() method. It accumulates the elements that are not found in the second array, resulting in the difference between the two arrays.

JavaScript
let a1 = [1, 2, 3, 4, 5]; let a2 = [3, 4, 5, 6, 7];  let res = a1.reduce((r, e) => {     if (a2.indexOf(e) === -1) {         r.push(e);     }     return r; }, []);  console.log(res);  

Output
[ 1, 2 ] 

5. Using Lodash _.difference() Function

Lodash _.difference() function is used to remove a single element or the array of elements from the original array. This function works pretty much the same as the core function of JavaScript i.e. filter.

JavaScript
let _ = require("lodash"); let a1 = [1, 2, 3]; let a2 = [2, 3] let res = _.difference(a1, a2); console.log(res); 

Output:

[1]

6. Using Array.filter() and Array.every() Methods

We are using the filter() method along with the every() method. We iterate over each element of the first array and check if it exists in the second array using the every() method. If an element is not found in the second array, it is included in the resulting array.

JavaScript
let a1 = [1, 2, 3, 4, 5]; let a2 = [3, 4, 5, 6, 7];  let res = a1.filter((e) => a2.every((val) => val !== e));  console.log(res); 

Output
[ 1, 2 ] 

7. Using Array find() and indexOf() Methods

This approach utilizes the find() method along with the indexOf() method to efficiently find elements in one array that are not present in the other array.

JavaScript
let a1 = [1, 2, 3, 4, 5]; let a2 = [3, 4, 5, 6, 7]; let res = a1.filter((e) => a2.indexOf(e) === -1); console.log(res);  

Output
[ 1, 2 ] 

Next Article
Difference between Array and Array of Objects in JavaScript

P

pranay0911
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • javascript-array
  • JavaScript-DSA
  • JavaScript-Questions

Similar Reads

  • Difference Between JavaScript Arrays and Objects
    Below are the main differences between a JavaScript Array and Object. FeatureJavaScript ArraysJavaScript ObjectsIndex TypeNumeric indexes (0, 1, 2, ...)Named keys (strings or symbols)OrderOrdered collectionUnordered collectionUse CaseStoring lists, sequences, ordered dataStoring data with key-value
    1 min read
  • Difference Between Array.from and Array.of in JavaScript
    JavaScript provides various methods for creating and manipulating arrays, two of which are Array.from and Array.of. These methods are part of the ECMAScript 6 (ES6) specification and offer distinct ways to create arrays. Understanding the differences between these two methods is important for effici
    3 min read
  • Difference between Array and Array of Objects in JavaScript
    ArrayAn Array is a collection of data and a data structure that is stored in a sequence of memory locations. One can access the elements of an array by calling the index number such as 0, 1, 2, 3, ..., etc. The array can store data types like Integer, Float, String, and Boolean all the primitive dat
    3 min read
  • How to get symmetric difference between two arrays in JavaScript ?
    In this article, we will see how to get the symmetric difference between two arrays using JavaScript. In Mathematics the symmetric difference between two sets A and B is represented as A Δ B = (A - B) ∪ (B - A) It is defined as a set of all elements that are present in either set A or set B but not
    6 min read
  • Print Difference between Two Objects in JavaScript ?
    Printing the difference between two objects in JavaScript involves comparing the properties of the two objects and identifying the discrepancies between them. This can include properties that exist in one object but not in the other, as well as properties with differing values. These are the followi
    3 min read
  • Difference Between array.reduce() and reduceRight() in JavaScript
    The array.reduce() and array.reduceRight() are two array methods used for reducing an array to a single value. They are particularly useful for performing cumulative operations on the array elements. Although they share similar functionality, their behaviour differs in the direction they iterate thr
    3 min read
  • Difference between forEach and for loop in Javascript
    In JavaScript, both forEach and for loops are used to iterate over arrays or collections, but they differ in usage and behavior. forEach is a higher-order function that simplifies iteration with built-in array methods, while for loops offer more control, flexibility, and broader application. For Loo
    4 min read
  • Difference between forEach() and map() loop in JavaScript
    The forEach() and map() methods in JavaScript are used to iterate over arrays, but they serve different purposes. forEach() executes a provided function once for each array element without returning a new array, while map() transforms elements and returns a new array. JavaScript forEach() JavaScript
    4 min read
  • Difference Between Variables and Objects in JavaScript
    The variables and objects are fundamental concepts but they serve different purposes. The Variables are used to store data values while objects are used to group related data and functions into a single entity. JavaScript VariableA variable in JavaScript is a named container that stores a value. It
    2 min read
  • Get the Difference between Two Sets using JavaScript
    To get the difference between two sets in JavaScript, you need to identify elements present in the first set but not in the second. This involves iterating over the first set and filtering out elements that are also found in the second set, ensuring efficient comparison. We can get the difference be
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences