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 a List of Array Keys in JavaScript?
Next article icon

How to filter Nested Array using Key in JavaScript ?

Last Updated : 05 Feb, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Filtering a nested array in JavaScript involves the process of selectively extracting elements from an array of objects, where each object contains another array. We will discuss how can we filter Nested Array using the key in JavaScript.

Filtering a nested array based on a key in JavaScript can be done using various methods:

Table of Content

  • Using filter method
  • Using reduce method
  • Using map and filter

Using filter method

The filter method is used to filter the main array based on a condition specified using the same method. The same method checks if at least one element in the nested array meets the given condition. This method directly filters the objects in the main array based on the specified key and value.

Example: This example shows the filtering of a nested array using the key by using the filter method.

JavaScript
// data taken const data = [     {         id: 1, items: [{ name: 'item1' },         { name: 'item2' }]     },     {         id: 2, items: [{ name: 'item3' },         { name: 'item4' }]     },     {         id: 3, items: [{ name: 'item5' },         { name: 'item6' }]     } ];  const keyToFilter = 'name'; const valueToFilter = 'item3';  const filteredData = data.filter(obj =>     obj.items.some(item => item[keyToFilter] === valueToFilter));  console.log(JSON.stringify(filteredData, null, 2)); 

Output
[   {     "id": 2,     "items": [       {         "name": "item3"       },       {         "name": "item4"       }     ]   } ] 

Using reduce method

The reduce() method is applied in this approach to iteratively build a new array that contains only the objects meeting the specified condition. The filter method is used to filter the items in the nested array, and the result is added to the accumulator array.

Example: This example shows the filtering of nested array using the key by using the reduce method.

JavaScript
const data = [   { id: 1, items: [{ name: 'item1' }, { name: 'item2' }] },   { id: 2, items: [{ name: 'item3' }, { name: 'item4' }] },   { id: 3, items: [{ name: 'item5' }, { name: 'item6' }] } ];  const keyToFilter = 'name'; const valueToFilter = 'item3';  const filteredData = data.reduce((acc, obj) => {   const filteredItems = obj.items.filter(item => item[keyToFilter] === valueToFilter);   if (filteredItems.length > 0) {     acc.push({ ...obj, items: filteredItems });   }   return acc; }, []);  console.log(JSON.stringify(filteredData, null, 2)); 

Output
[   {     "id": 2,     "items": [       {         "name": "item3"       }     ]   } ] 

Using map and filter

The map and filter methods to achieve the desired result. First, the map method is used to iterate over each object in the main array. Then, the filter method is applied to the nested array within each object, isolating only the items that match the specified key and value.

Example: This example shows the filtering of a nested array using the key by using the map and filter method.

JavaScript
const data = [   { id: 1, items: [{ name: 'item1' }, { name: 'item2' }] },   { id: 2, items: [{ name: 'item3' }, { name: 'item4' }] },   { id: 3, items: [{ name: 'item5' }, { name: 'item6' }] } ];  const keyToFilter = 'name'; const valueToFilter = 'item3';  const filteredData = data.map(obj => ({   ...obj,   items: obj.items.filter(item => item[keyToFilter] === valueToFilter) })).filter(obj => obj.items.length > 0);  console.log(JSON.stringify(filteredData, null, 2)); 

Output
[   {     "id": 2,     "items": [       {         "name": "item3"       }     ]   } ] 

Next Article
How to Get a List of Array Keys in JavaScript?

J

jaykush
Improve
Article Tags :
  • JavaScript
  • Web Technologies

Similar Reads

  • How to store a key=> value array in JavaScript ?
    In JavaScript, storing a key-value array means creating an object where each key is associated with a specific value. This allows you to store and retrieve data using named keys instead of numeric indices, enabling more intuitive access to the stored information. Here are some common approaches: Tab
    4 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
  • How to use map() filter() and reduce() in JavaScript?
    The map(), filter(), and reduce() are the array functions that allow us to manipulate an array according to our logic and return a new array after applying the modified operations on it. 1. JavaScript map() MethodThe map() method in JavaScript is used to create a new array by applying a function to
    2 min read
  • How to filter nested objects in JavaScript?
    The filter() method creates a new array with all elements that pass the test implemented by the provided function. Below are the approaches used to filter nested objects in JavaScript: Table of Content Using filter() methodUsing some() method Method 1: Using filter() method Example: This approach us
    2 min read
  • How to Get a List of Array Keys in JavaScript?
    Here are the different methods to get a list of associative array keys in JavaScript 1. Using JavaScript for each loopIn this method, traverse the entire associative array using a for each loop and display the key elements of the array. [GFGTABS] javascript //Driver Code Starts{ let a = {Newton:
    3 min read
  • How to flatten array with the JavaScript/jQuery?
    Flattening an array in JavaScript or jQuery involves transforming a nested array into a single-level array. This process is essential for simplifying complex data structures and making it easier to manipulate and access array elements. Below are the approaches to flatten an array with JavaScript/Jqu
    3 min read
  • How to filter out the non-unique values in an array using JavaScript ?
    In JavaScript, arrays are the object using the index as the key of values. In this article, let us see how we can filter out all the non-unique values and in return get all the unique and non-repeating elements. These are the following ways by which we can filter out the non-unique values in an arra
    4 min read
  • How to Move a Key in an Array of Objects using JavaScript?
    The JavaScript array of objects is a type of array that contains JavaScript objects as its elements. You can move or add a key to these types of arrays using the below methods in JavaScript: Table of Content Using Object Destructuring and Map()Using forEach() methodUsing for...of LoopUsing reduce()
    5 min read
  • How to Create a Nested Object in JavaScript ?
    JavaScript allows us to create objects having the properties of the other objects this process is called as nesting of objects. Nesting helps in handling complex data in a much more structured and organized manner by creating a hierarchical structure. These are the different methods to create nested
    4 min read
  • How to remove object from array of objects using JavaScript ?
    Removing an object from an array of objects in JavaScript refers to the process of eliminating a specific object from the array based on certain conditions, like matching a property value. This task is common in data manipulation, ensuring the array only contains the desired elements. There are two
    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