What is the best way to search for and isolate an array object within an array of objects using Javascript?

I am attempting to narrow down the list based on offerings

const questions = [
    { "id": 2616, "offerings": [{"code": "AA"},{"code": "AB"}]},
    { "id": 1505, "offerings": [{"code": "AA"},{"code": "ABC"}]},
    { "id": 1500, "offerings": [{"code": "AC"},{"code": "DC"}]}
];

const filterByArray = ['AB', 'DC'];

My desired result is to retrieve elements that match the items in the filterByArray

[
    { "id": 2616, "offerings": [{"code": "AA"},{"code": "AB"}]},
    { "id": 1500, "offerings": [{"code": "AC"},{"code": "DC"}]}
]

I have attempted filtering the array using

var filtered = questions.filter(function(element) {
    return element.offerings.filter(function(cd) {
       return filterByArray.indexOf(cd.code) > -1;
    }).length === filterByArray.length;
});

console.log(filtered)

However, it keeps returning all elements in the array.

Answer №1

Utilize the Array.some() method along with Array.includes().

const questions = [
    { "id": 2616, "offerings": [{"code": "AA"},{"code": "AB"}]},
    { "id": 1505, "offerings": [{"code": "AA"},{"code": "ABC"}]},
    { "id": 1500, "offerings": [{"code": "AC"},{"code": "DC"}]}
];

const filterByArray = ['AB', 'DC'];

const output = questions.filter(q => q.offerings.some(o => filterByArray.includes(o.code)));

console.log(output);

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

What role does the "deep" parameter serve when declaring a watcher in VueJS?

I recently discovered a feature in Vue.js called watchers while working on my web app. As I was exploring the API documentation, I came across a flag known as deep. This flag caught my attention because it defaults to false. I'm curious to know what s ...

Comparing strings with data in objects using Angular

all. I have a query. What is the optimal method for comparing data? For instance, if you have a constant response = 225235743; And I aim to locate and exhibit all data in an object with the same ID as the one in this response. This needs to be resolved ...

Retrieve a JSON array using an HTTP Get request in JavaScript (with jQuery)

I’ve been experimenting with various code snippets in an attempt to reach my objective, but so far I haven’t found a solution. Objective: My goal is to retrieve a JSON array of objects from a specific web URL using the GET method. This task needs to b ...

What is the correct way to express an object in an array?

I've encountered an issue: I'm working with an array called _daysConfig<DayConfig> When I manually populate it like this, everything functions correctly: _daysConfig: DayConfig[] = [ { date: new Date('Wed Jul 22 2020 21:06:00 GMT+02 ...

Put identical objects into several arrays at the same time

This question is in relation to a previous query about arranging 3 arrays to correspond with each other. After creating my objects, I am now attempting to push values into their respective arrays based on JSON data received. let objName = ["object1", "obj ...

Adjusting the value of 'let' based on the outcome

Can you assist me with this issue? I am attempting to assign a value to a let variable based on the following if conditional block. class Main extends React.Component{ render(){ let content = ''; firebase.auth().onAuthStateChanged(func ...

The sort function in Reactjs does not trigger a re-render of the cards

After fetching data from a random profile API, I am trying to implement a feature where I can sort my profile cards by either age or last name with just a click of a button. Although I managed to get a sorted array displayed in the console log using the h ...

A guide on retrieving and resetting the value of a radio button within a table

I need to create multiple radio buttons within a table using Razor syntax under ASP.NET Core MVC. Each row of the table should have an update and clear link to update the record and clear the selected radio button for that specific row. <table class=&qu ...

Utilizing Laravel's Collection to Retrieve an Array Containing Objects

I am attempting to retrieve an array of objects with my Laravel collection by using this code snippet: /** * View a user's chat rooms. * * return \Illuminate\Http\Response|\Laravel\Lumen\Http\ResponseFactory&bsol ...

Is it possible to create a table using a loop in an SQLite query?

Welcome In the company where I work, Excel is currently being used to manage a large database of items for cost estimation purposes. To simplify this process, I am developing an Electron App that will replace Excel with a more user-friendly interface and ...

What is the best way to create a list using only distinct elements from an array?

If I have a collection of different colors: Red Blue Blue Green I aim to extract only the unique colors and store them in an array. Subsequently, I plan to incorporate each color from that array into an existing color list. The desired outcome would l ...

jQuery slider - display unlimited images

Currently, I am encountering issues with a Flickity carousel of images. When an image/slide is clicked, a modal window opens to display a zoomed-in version of the image. The problem arises when there are more or fewer than 3 images in the slider — my cod ...

The act of appending values to an array within a hash in Vue is not functioning as expected

I am currently working on implementing a feature that allows users to add multiple workers by clicking the "Add worker" button. However, I have encountered an issue where placing the workers array inside the management object prevents this feature from f ...

Using JavaScript in PHP files to create a box shadow effect while scrolling may not produce the desired result

Issue at hand : My JavaScript is not functioning properly in my .php files CSS not applying while scrolling *CSS Files are named "var.css" #kepala { padding: 10px; top: 0px; left: 0px; right: 0px; position: fixed; background - c ...

Get a numerical value from a JSON object

Attempting to retrieve information from an API, but encountering an issue due to a numeric property name. The method for accessing the data is as follows: Success: data[i].price_usd Unsuccessful Attempt: data[i].24h_volume_usd Have experimented with ...

How can I make a basic alert box close after the initial click?

After clicking a button, I have a simple jQuery script that triggers a fancybox. However, the issue is that the fancy box does not close after the first click of the button; it only closes after the second click... Another problem arises inside the fancy ...

Make sure link opens in the same window/tab

Currently, I am utilizing the Open Link in Same Tab extension on Google Chrome. This extension can be found here. The purpose of this extension is to ensure that all links open in the same window/tab, which is necessary for touch screen kiosk left/right s ...

Is there a way to transfer PHP user information (session) to a Node.js server?

Currently, I have two separate pages set up for my website. One is the Chat page, which operates on Node.js and Socket.io using WebSockets. The other is the main page where users login and access various features. I am looking to implement a system where, ...

Screen remains blank as the React webpage fails to load

Hello, I am having issues with my React page not showing up. Can someone please review my code to see if there are any errors? Here is the edited program: index.html <!doctype html> <html lang="en"> <head> <meta charset ...

Utilizing jquery.validate.min.js for efficient form validation

Here is my JavaScript validate function: $("form[id='form']").validate({ Name: "required", submitHandler: function() { formSubmit(); } }); Not only do I wa ...