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:
How to Get all Elements Except First in JavaScript Array?
Next article icon

How to Filter an Array from all Elements of another Array In JavaScript?

Last Updated : 22 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Filtering one array from all elements of another array is a common task in JavaScript. This involves removing elements from one array that are present in another array. In this article we will explore different approaches to filter an array from all elements of another array in JavaScript.

These are the approaches to filter an array from all elements of another array in JavaScript

Table of Content

  • Using for Loop
  • Using filter and includes Methods
  • Using Set
  • Using reduce Method
  • Using map for Additional Operations
  • Using forEach Method

Using for Loop

In this approach we will use a for loop to iterate through the first array (arr1) and check if each element’s presence in the second array (arr2) using includes.

Example: In this example we are using for loop to filter an array from all elements of another array in JavaScript. The final array will be shown in the console.

JavaScript
const arr1 = [10, 20, 30, 40, 50]; const arr2 = [30, 50]; const result = []; for (const item of arr1) {     if (!arr2.includes(item)) {         result.push(item);     } } console.log(result); 

Output:

[ 10, 20, 40 ]

Using filter and includes Methods

In this approache we will use the filter and includes methods. The filter method goes through each element of the array and applies a test function to determine if the element should be included in the new array. The includes method checks if a specific value exists in an array.

Example: In this example we are using filter and includes Methods to filter an array from all elements of another array in JavaScript.

JavaScript
const arr1 = ['a', 'b', 'c', 'd', 'e']; const arr2 = ['c', 'd', 'e'];  const result = arr1.filter(item => !arr2.includes(item));  console.log(result); 

Output:

[ 'a', 'b' ]

Using Set

In this approach we will use a Set which is an efficient way to filter elements because lookup operations in a Set are generally faster compared to arrays.

Example: In this example we are using set to filter an array from all elements of another array in JavaScript. The final array will be shown in the console.

JavaScript
const array1 = [1, 2, 3, 4, 5]; const array2 = [2, 4];  const filteredArray = array1.filter(item => !new Set(array2).has(item));  console.log(filteredArray); 

Output:

[ 1, 3, 5 ]

Using reduce Method

Using reduce method allows us to accumulate a result by iterating through the array, which can also be used to filter out elements.

Example: In this example we are using reduce method to filter an array from all elements of another array in JavaScript. The final array will be shown in the console.

JavaScript
const array1 = [1, 2, 3, 4, 5]; const array2 = [2, 4];  const filteredArray = array1.reduce((acc, item) => {     if (!array2.includes(item)) {         acc.push(item);     }     return acc; }, []);  console.log(filteredArray); 

Output:

[ 1, 3, 5 ]

Using map for Additional Operations

In this approach we will use the map which creates a new array by applying a function to each element of the original array. map is not typically used for filtering but we can combine it with filter to perform additional operations on the filtered results.

Example: In below example we are filtering array and also we are performing multiplication operation on filtered array using map. The final array will be shown in the console.

JavaScript
const array1 = [1, 2, 3, 4, 5]; const array2 = [2, 4];  const filteredArray = array1     .filter(item => !array2.includes(item))     .map(item => item * 2);  console.log(filteredArray); 

Output:

[ 2, 6, 10 ]

Using forEach Method

The forEach method provides a straightforward way to iterate over each element of an array and perform operations. Unlike map or filter, forEach does not return a new array by itself, instead we have to manually create and populate a new array during the iteration.

Example: In this example we are using forEach method to filter an array from all elements of another array in JavaScript. The final array will be shown in the console.

JavaScript
const array1 = [1, 2, 3, 4, 5]; const array2 = [2, 4];  const filteredArray = []; array1.forEach(item => {     if (!array2.includes(item)) {         filteredArray.push(item);     } });  console.log(filteredArray); 

Output:

[ 1, 3, 5 ]

Next Article
How to Get all Elements Except First in JavaScript Array?
author
yuvrajghule281
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • JavaScript-Questions

Similar Reads

  • JavaScript - How to Remove an Element from an Array?
    Removing elements from an array is a fundamental operation in JavaScript, essential for data manipulation, filtering, and transformation. This guide will explore different methods to efficiently remove elements from an array, enhancing your understanding and capability in handling arrays. 1. Using p
    3 min read
  • JavaScript - How to Get First N Elements from an Array?
    There are different ways to get the first N elements from array in JavaScript. Examples: Input:arr = [1, 2, 3, 4, 5, 6], n = 3 Output: [1, 2, 3] Input:arr = [6, 1, 4, 9, 3, 5, 7], n = 4Output: [6, 1, 4, 9]1. Using slice() MethodThe slice() method is used to extract a part of an array and returns a n
    4 min read
  • How to Merge/Flatten an array of arrays in JavaScript ?
    Merging or flattening an array of arrays in JavaScript involves combining multiple nested arrays into a single-level array. This process involves iterating through each nested array and appending its elements to a new array, resulting in a flattened structure. To Merge or flatten array we can use ar
    3 min read
  • How to Get all Elements Except First in JavaScript Array?
    Here are the various methods to get all elements except the first in JavaScript Array 1. Using for loopWe will use a for loop to grab all the elements except the first. We know that in an array the first element is present at index '0'. [GFGTABS] JavaScript const a1 = [1, 2, 3, 4, 5]; const a2 = [];
    4 min read
  • How to Remove duplicate elements from array in JavaScript ?
    In this article, we will discuss the methods to remove duplicate elements from a Javascript array. There are various methods to remove duplicates in the array. These are the following ways: Table of Content Using filter() MethodUsing set() MethodUsing forEach() MethodUsing reduce() MethodUsing index
    4 min read
  • How to Create Nested Arrays from a Nest of Arrays in JavaScript ?
    Creating nested arrays from a nest of arrays in JavaScript involves organizing multiple arrays into a hierarchical structure, which is often useful for managing and representing complex data relationships. This process entails encapsulating arrays within other arrays to form multi-dimensional struct
    3 min read
  • How to Check if an Element Exists in an Array in JavaScript?
    Given an array, the task is to check whether an element present in an array or not in JavaScript. If the element present in array, then it returns true, otherwise returns false. The indexOf() method returns the index of first occurance of element in an array, and -1 of the element not found in array
    2 min read
  • How to delete an element from an array using JavaScript ?
    The array is a type of data structure that allows us to store similar types of data under a single variable. The array is helpful to create a list of elements of similar types, which can be accessed using their index. In this article, we will discuss different ways to remove elements from the array.
    5 min read
  • How to Convert an Array into a Complex Array JavaScript ?
    Complex arrays can represent multiple dimensions or data with a structure. This article discusses two approaches to converting an array into a more complex array. Table of Content Using Multidimensional ArraysUsing Array.from()Using the reduce() MethodUsing the map() Method with slice() MethodUsing
    3 min read
  • How to Filter an Array in JavaScript ?
    The array.filter() method is used to filter array in JavaScript. The filter() method iterates and check every element for the given condition and returns a new array with the filtered output. Syntax const filteredArray = array.filter( callbackFunction ( element [, index [, array]])[, thisArg]);Note:
    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