How can I successfully filter a nested array in javascript using values from the array in order to also make it compatible with single values?

In exploring this issue further, I discovered an interesting example from a different topic. This example involves filtering a nested array within another array based on specified filter values.

Curiously, the method used in this example doesn't work effectively when there is only a single element in the array.

const data = [
        {
            "guid": "j5Dc9Z",
            "courses": [
                {
                    "id": 3,
                    "name": "foo"
                }
            ]
        },
        {
            "guid": "a5gdfS",
            "courses": [
                {
                    "id": 1,
                    "name": "bar"
                },
                {
                    "id": 3,
                    "name": "foo"
                }
            ]
        },
        {
            "guid": "jHab6i",
            "courses": [
                {
                    "id": 7,
                    "name": "foobar"
                }
            ]
        }
    ];

    const courses = [3];
    const result = data.filter(item => item.courses.every(course => courses.includes(course.id)));
    console.log(result);
    

In the context of this specific scenario, we would expect to see two instances of the value '3', but instead, we are only getting the first one. How can we improve this filtering process for nested arrays with both multiple and single values?

Answer №1

You have requested for every single object to have an id of 3, but what you really need is for some or any of the objects to contain the id 3, as shown below:

const data = [{
    "guid": "j5Dc9Z",
    "courses": [{
      "id": 3,
      "name": "foo"
    }]
  },
  {
    "guid": "a5gdfS",
    "courses": [{
      "id": 1,
      "name": "bar"
    }, {
      "id": 3,
      "name": "foo"
    }]
  }, {
    "guid": "jHab6i",
    "courses": [{
      "id": 7,
      "name": "foobar"
    }]
  }
];
const courses = [3];
const result = data
  .filter(d => d.courses.some(c => courses.includes(c.id)))
  .map(d => ({ ...d, courses: d.courses.filter(c => courses.includes(c.id))
  }));
console.log(result);

Answer №2

If you're searching for items in the data that contain all the ids listed in the const courses, you'll need to reverse your filtering technique.

const data = [
  {"guid": "j5Dc9Z", "courses": [{"id": 3, "name": "foo"}]},
  {"guid": "a5gdfS", "courses": [{"id": 1, "name": "bar"}, {"id": 3, "name": "foo"}]}, 
  {"guid": "jHab6i", "courses": [{"id": 7, "name": "foobar"}]}
];

const courses = [3];
const r = data.filter(d => courses.every(courseId => d.courses.find(({
  id
}) => courseId === id)));
console.log(r);

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

Steps to open and configure a Mobile-Angular modal from another controller

Is it possible to use a modal in Angular JS for mobile devices without compromising the layout? I'm having trouble setting up the controller for my modal inside my main controller and passing parameters. Should I consider using ui-bootstrap for this p ...

What sets apart `Object.merge(...)` from `Object.append(...)` in MooTools?

This question may seem simple at first glance, but upon further inspection, the MooTools documentation for the 'append' and 'merge' methods appears to be identical. Here is the code snippet provided in the documentation: var firstObj ...

"Is it possible to include a button for horizontal scrolling in the table

I have a bootstrap table with overflowing set to auto within its container, along with a locked first column. While a horizontal scroll bar allows for viewing additional data, I am looking to incorporate buttons for navigation as well. Users should have th ...

Is it possible to trigger a JavaScript function and an AJAX command with just one button click?

I'm looking to achieve a specific functionality using one button within a form. The requirements are as follows: 1) When the button is clicked, it should trigger a JavaScript function that performs animations such as fadeout and fadein. 2) Following ...

Creating objects based on interfaces in TypeScript is a common practice. This process involves defining

Within my TypeScript code, I have the following interface: export interface Defined { 4475355962119: number[]; 4475355962674: number[]; } I am trying to create objects based on this interface Defined: let defined = new Defined(); defined['447 ...

Creating a POST request in a C# web application

I am currently attempting to submit a form using C# After conducting some research, I have been having trouble coding it correctly (as I am new to this field). Below are the snippets of code I have: View; <form> <div class="field-wra ...

Troubleshooting WebRTC issues when trying to record video

I recently tested out the functionality of , but unfortunately, it seems to be encountering issues on iPhone when using Safari or Chrome. The errors are related to getUserMedia. These errors are happening by default and I have not made any changes to my s ...

Leveraging viewbag information in combination with jQuery JSON techniques

I have a desire to utilize my ViewBag within a JavaScript array. After researching on using viewbag with jquery asp.net mvc 3, I believe I found the code that suits my needs: @model MyViewModel <script type="text/javascript"> var model = @Html. ...

Turn off the incorrect TypeScript error detection

After setting up 'interact.js' using jspm and npm for TypeScript compatibility, I am encountering errors in my code: import { interact } from 'interact.js/interact' // ==> typescript error: TS2307: Cannot find module 'interact. ...

Cluster associative array elements based on their values while keeping the original keys intact within each cluster

I am looking for a way to group Associative Arrays with their `keys. Currently, I am unsure of the correct syntax to achieve this. Here is the code I have at the moment: $associativeArray = array("Ripe Mango"=>"Yellow", "Strawberry"=>"Red", "Lemon" ...

Unable to properly display the message in Angular

<!DOCTYPE html> <html ng-app> <head> <script data-require="angular.js@*" data-semver="1.4.3" src="https://code.angularjs.org/1.4.3/angular.js"></script> <link rel="stylesheet" href="style.css" /> ...

While attempting to upload a file in my Mocha Node.js test, I encountered the message: "Received [Object null prototype] { file: { ... }}"

Everywhere I find the solution in white : app.use(bodyParser.urlencoded({extended: true})); I can use JSON.stringify(req.files) However, I am sure there is a way to fix my problem. My Mocha test : it('handles file upload', async function () { ...

Clearing the JSON data from the file object

I am encountering an issue that requires me to pass some information along with a file to a controller using an Ajax call. The model structure is as follows: public class PersonModel { [Display(Name ="Full Name")] public string Name { ...

What is the best method to retrieve the country name from a world map using D3.js?

I'm trying to figure out how to retrieve the country name from a click event on the D3 world map. Despite inspecting the DOM, I can't quite understand how the country's name, code, or population is associated with the map. The template for ...

Troubles with proper functionality of antd's DatePicker.RangePicker within a React Function Component

I am currently utilizing React and the antd library, attempting to incorporate the DatePicker.RangePicker into my project. Initially, when I directly embed the RangePicker within the component, everything works smoothly. However, for better code organizat ...

CSS margin-left causing issues in Chrome Extension

My current situation is incredibly puzzling, as I am at a loss for what is happening. I developed a Firefox add-on using jQuery and CSS to revamp a website. When attempting to transfer the add-on to Chrome (which was relatively straightforward due to the s ...

What is the best way to include query parameters in a redirect using the res.redirect function in node.js/express.js?

Trying to navigate users to a Google Authorization page within my application poses a challenge. In this scenario, utilizing any Google API modules is not an option. To achieve the redirection, I am aware that I can structure my res.redirect() function in ...

Sending a function along with event and additional arguments to a child component as a prop

I've managed to set up a navigation bar, but now I need to add more complexity to it. Specifically, I have certain links that should only be accessible to users with specific permissions. If a user without the necessary permissions tries to access the ...

Is it possible to read a file with a different dynamically generated name each time in Cypress?

Being new to Cypress, I am faced with the challenge of writing a test case to verify the download of a file. Despite researching various resources on similar test cases, they all involve reading a file with a static name. In my scenario, the file is downlo ...

How can one generate a custom link using vue-router in Vue.js after the rendering process has been completed?

Currently, I am utilizing VUE and I must say, boostrap-table is performing admirably! Within my component, I have the following: <BootstrapTable :columns="table.columns" :data="table.data" :options="table.options"></ ...