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

Show the Vue.js template in a Laravel Blade view

I have been struggling to integrate a Vue.js component into a Laravel blade file. Despite researching tutorials and Stack Overflow solutions, I have not been able to resolve the issue. Below is the template that I want to display: <template> < ...

Attempting to create a JavaScript class within an HTML document

Having an issue with instantiating a JavaScript class in a separate HTML file. The JavaScript class looks like this: class Puzzle { constructor(fenStart, pgnEnd) { this.fenStart = fenStart; this.pgnEnd = pgnEnd; } } module.exports = Puzzle; ...

Using TypeScript, apply an event to every element within an array of elements through iteration

I have written the code snippet below, however I am encountering an issue where every element alerts the index of the last iteration. For instance, if there are 24 items in the elements array, each element will alert "Changed row 23" on change. I underst ...

You cannot add properties to an object within an async function

I am attempting to include a fileUrl property in the order object within an async function, but I am unable to make it work properly. My expectation is for the order object to contain a fileUrl property once added, but unfortunately, it does not seem to b ...

JQuery is having trouble with playing multiple sound files or causing delays with events

I've been working on a project that involves playing sounds for each letter in a list of text. However, I'm encountering an issue where only the last sound file is played instead of looping through every element. I've attempted to delay the ...

What is the functionality of the toArray method?

var retrieveDocs = function (db, callback) { var collection = db.collection('tours'); collection.find({ "tourPackage": "Snowboard Cali" }).toArray(function (err, data) { console.log(data); callback; }) } Is there a p ...

The Vue.js application is failing to toggle the integrated code

I am new to using Vue and I am trying to create a vertical navigation bar. When the menu icon is clicked, the navbar should toggle. Here is my menu icon code: <button type="button" id="sidebarCollapse" class="btn btn-info [collapsed?'': ...

Put a cookie in place to deter users from returning to the website

Looking for a way to prevent access to my contest site once the form has been submitted. Is there a way to achieve this? Thanks in advance ...

Tips for incorporating inline styling into the body element

Can someone help me with adding inline style to the body element using jQuery? I want to set the background color to white (#FFFFFF). Your assistance would be highly appreciated. Thank you! ...

I am experiencing difficulties with my focusin not functioning properly for the input element that I added

I am working on a program that includes a dynamic table with the following structure: <table id="selectedItems"> </table> I plan to use jQuery to append elements to it like so: var i=0; $("#selectedItems").html(''); $("#sel ...

Attempting to replicate the functionality of double buffering using JavaScript

In my HTML project, I have a complex element that resembles a calendar, with numerous nested divs. I need to refresh this view in the background whenever there are updates on the server. To achieve this, I set up an EventSource to check for data changes on ...

Issue: Module "expose?Zone!zone.js" could not be located

Just started experimenting with Angular 2 and encountering an issue when importing zone.js as a global variable: https://i.stack.imgur.com/gUFGn.png List of my packages along with their versions: "dependencies": { "angular2": "2.0.0-beta.3", "es ...

How to access a static TypeScript variable in Node.js across different files

I encountered a situation like this while working on a node.js project: code-example.ts export class CodeExample { private static example: string = 'hello'; public static initialize() { CodeExample.example = 'modified'; } ...

Start the setInterval function again after clearing it with the clearInterval button, but wait for

Currently, I am working on a content slider that automatically cycles through slides using the "next" function and setInterval. However, I want it to stop when the user clicks on the prev/next buttons by using clearInterval. Is there a way to resume setInt ...

Analyzing User Input and Database Information with Mongodb

Here's the HTML form I'm working with: <form id="contact-form" method="POST" action="/search"> <label for="company">Phone company</label> <input type="text" name="company" value=""> &l ...

"Efficiently extracting specific characters from an array and returning them as a new string in Laravel 7

I am seeking guidance on how to return a string for any array part of my request. The keys in the request are dynamic, so hard coding is not an option. Here is an example of my current approach. $request = [ 'empresaId' => '2', ...

What is the best way to showcase all menu and submenu items in separate dropdown lists?

Having trouble with my code, it's not functioning properly. I can't pinpoint the error. The menu displays correctly but the submenu isn't showing up under specific menus. Here is the code snippet: ##Table: menus## id name ...

Solving an object in ui-router state using ui-sref

Dealing with a large JSON object in an Angular controller and wanting to pass it to the controller of a template that will be displayed in a ui-view. I am aware that parameters can be passed to states using ui-sref, but I do not want this object to be visi ...

How to use jQuery with multiple selectors?

I am attempting to create a feature where multiple links are highlighted when one is clicked. However, I am encountering an issue where only the link that is clicked is being highlighted, rather than all three links. Below is the code snippet: $('#v ...

Discover the initial item in Observable that meets a certain criteria

I am trying to retrieve the first item of type avatar from payload.result within an observable: let result = this.fileService.getAvatarByUserId(2).pipe( map((payload: Payload<FileModel[]>) => payload.result), first((result: FileModel[]) => ...