Filter an array of objects based on specific conditions that must be met by their children

I am facing the challenge of parsing through an array of objects that contain embedded arrays of objects. My goal is to use .filter() to achieve this, but I need to verify if the embedded array includes at least one of several specified object types. Allow me to illustrate using an example:

Imagine an array of Garage objects with a "cars" field, which consists of an array of cars. Each car is represented as an object with an array of qualities. I want to identify the garages that have at least one "fast" car and at least one "tiny" car. It's acceptable for a single car to possess both qualities. How can I efficiently accomplish this task in JavaScript?

garageArray = [
 {
  id: 10,
  cars: [
   {id: 1, qualities: ["fast", "small"]},
   {id: 2, qualities: ["offRoad", "large"]},
   {id: 3, qualities: ["fast", "loud"]}
  ]
 },
 {
  id: 20,
  cars: [
   {id: 4, qualities: ["loud"]},
   {id: 5, qualities: ["fast", "tiny"]}
  ]
 },
 {
  id: 30,
  cars: [
   {id: 6, qualities: ["slow", "small"]},
   {id: 7, qualities: ["offRoad", "tiny"]},
   {id: 8, qualities: ["fast", "loud"]}
  ]
 }
]

The desired outcome should consist of Garages with the ids of 20 and 30.

Answer №1

Here is a code snippet that should accomplish the task:

garageArray.filter(garage =>
    garage.cars.some(car => car.qualities.includes("fast")) &&
    garage.cars.some(car => car.qualities.includes("tiny"))
);

For a more versatile solution to match any number of properties, you can use the following code:

const garageArray = [
    {
        id: 10,
        cars: [
            { id: 1, qualities: ["fast", "small"] },
            { id: 2, qualities: ["offRoad", "large"] },
            { id: 3, qualities: ["fast", "loud"] }
        ]
    },
    {
        id: 20,
        cars: [
            { id: 4, qualities: ["loud"] },
            { id: 5, qualities: ["fast", "tiny"] }
        ]
    },
    {
        id: 30,
        cars: [
            { id: 6, qualities: ["slow", "small"] },
            { id: 7, qualities: ["offRoad", "tiny"] },
            { id: 8, qualities: ["fast", "loud"] }
        ]
    }
];

var featuresTofind = ["loud", "fast", "tiny"];

var result = garageArray.filter(function (garage) {
    var featuresFound = featuresTofind.filter(function (feature) {
        return garage.cars.some(function (car) {
            return car.qualities.includes(feature);
        });
    });
    return featuresFound.length === featuresTofind.length;
});

console.log(result);

Answer №2

One potential inconvenience is having to loop through the cars twice; I trust this is acceptable.

garageArray.filter(garage => {
    return garage.cars.some(car => {
        return car.qualities.includes("fast")
    }) && garage.cars.some(car => {
        return car.qualities.includes("tiny")
    });
})

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

Unexpected Error Occurs When Attempting to Update jQuery Version with AJAX Post Request

My challenge involves working with multiple radio elements, each with different names and values. When a radio button is clicked, I need to send the data to the server using AJAX. Here is my current AJAX method: $("input[type=radio]").click(function() { ...

Is there a way to view a list of URLs all at once in a single window?

Is there a way to open multiple URLs in a single tab? I have a list of URLs that I want to open and cache the contents without cluttering my browser with numerous tabs. ...

Challenge encountered when trying to store AngularJS response in a global variable

When making an HTTP call to the controller using angular.js, I am trying to save the response in a global variable like so: app.controller('dashBoardController', ['$scope', '$http', '$location', function ($scope ...

Retrieve the final ID of a dynamic div

Unable to find a solution, I am attempting to retrieve the ID of the most recently created div on the page. The code I have been using with .last() doesn't seem to be functioning correctly. My syntax may be incorrect, as I can't seem to extract a ...

Retrieve anchor elements from multiple HTML documents

I have a challenge that I'm not certain is achievable, but I am attempting to extract all anchor tag links from several HTML files on my website. Currently, I have developed a PHP script that scans various directories and subdirectories to create an a ...

making a request on an object that includes an array representation of another object

Here is the JSON data I have: [ { "RouteNo": "004", "RouteName": "POWELL/DOWNTOWN/UBC", "Direction": "WEST", "Schedules": [ { "Destination": "UBC", "ExpectedCountdown": -4, }, { "Destination": ...

Tips for enhancing shadow clarity in three.js

Within a scene, there are multiple objects that I want to move across a wide plane that is capable of receiving shadows. However, when using only one point light or a very large directional light, the shadows cast by the objects tend to have rough edges, e ...

Ways to prevent AJAX from triggering multiple requests

I am currently using the jQuery countdown timer plugin from Keith Wood's website to showcase the time. I have a function set up to add extra time when the 'onTick' callback event is triggered. However, whenever the countdown reaches 00:00:00 ...

What purpose do controller.$viewValue and controller.$modelValue serve in the Angular framework?

I'm confused about the connection between scope.ngModel and controller.$viewValue/controller.$modelValue/controller.$setViewValue(). I'm specifically unsure of the purpose of the latter three. Take a look at this jsfiddle: <input type="text" ...

No children were located within the div element

Presently, I am attempting to disable an image for the initial element in each faqs div class in HTML. To achieve this, I am aiming to target the parent element of faqs and then navigate downwards to locate the initial list element using the following Java ...

Refreshing MVC5 Partial View with Embedded Document Viewer

In my MVC5 partial view, there is a document viewer and an upload button for users to add documents. I need to refresh the partial view or reload it completely after a document is uploaded so that the newly uploaded document is immediately visible. Below ...

Did I incorrectly pass headers in SWR?

After taking a break from coding for some time, I'm back to help a friend with a website creation project. However, diving straight into the work, I've encountered an issue with SWR. Challenge The problem I'm facing is related to sending an ...

I am experiencing difficulty in retrieving the result for the following code snippet

I'm currently attempting to retrieve data for my chart from a data.csv file. <!DOCTYPE html> <html> <head> <title>D3 test</title> <style> .grid .tick { ...

Passing values from a Laravel controller to a Vue component as a prop

At the moment, I have a Laravel route that directs to the index function of my controller with an ID passed, where I then return the ID in a view. public function index($id) { return view('progress') ->with('identifier', ...

Launch a puppeteer instance in gitpod

When I initiate the npm run start command, this issue occurs: TROUBLESHOOTING: https://github.com/puppeteer/puppeteer/blob/main/docs/troubleshooting.md at onClose (/workspace/zanoni-bot/node_modules/puppeteer/lib/cjs/puppeteer/node/BrowserRunner.js:28 ...

Guide to dynamically resizing the Monaco editor component using react-monaco-editor

Currently, I am integrating the react-monaco-editor library into a react application for viewing documents. The code snippet below showcases how I have set specific dimensions for height and width: import MonacoEditor from 'react-monaco-editor'; ...

extensive collections with numerous empty slots

In my Java program, I currently have a line of code that initializes a multi-dimensional array like this: double[][][][][][][][][][][] array = new double[20][10][9][8][5][4][4][3][3][3][2]; Since most of these entries will remain as null, I'm wonder ...

Searching for a specific string within an array

Is there a way to check if a specific string exists in an array? I need to implement the following logic: if (getUsers().containsString(userInput.text!) == false) { print("hello") alert("Oops, you'll need to make a change", text2: "That use ...

Zod: Generate a basic item using default settings

I have a strong belief that this concept exists, however, my research has not yielded any results. Let's consider a scenario where I have a zod Schema structured like this: const Person = zod.object({ name: z.string().default(''), ag ...

What could be the reason for the Javascript function failing to run?

I need assistance in executing a function called "send()" which includes an AJAX request. This function is located in ajax.js (included in the code snippet) The Ajax success updates the src attribute of my image. The function seems to be working correctly ...