Sort through an array using criteria from another array

const items = [[{name:"p2"},{name:"p3"}, {name:"p7"},{name:"p9"},{name:"p1"}],[{name:"p6"}, {name:"p3"},{name:"p7"}, {name:"p9"},{name:"p2"}],[{name:"p3"},{name:"p6"}, {name:"p7"},{name:"p9"},{name:"p4"}],[{name:"p2"}, {name:"p3"},{name:"p1"}, {name:"p9"},{name:"p6"}]]

const findObj = [{name:"p1"},{name:"p2"},{name:"p6"}]

Locate the array within the sets that contains all three elements from the findobj object

Answer №1

To achieve the desired outcome, you can utilize filter, Set, and reduce. Here's an example:

const items = [
  [
    { name: "p2" },
    { name: "p3" },
    { name: "p7" },
    { name: "p9" },
    { name: "p1" },
  ],
  [
    { name: "p6" },
    { name: "p3" },
    { name: "p7" },
    { name: "p9" },
    { name: "p2" },
  ],
  [
    { name: "p3" },
    { name: "p6" },
    { name: "p7" },
    { name: "p9" },
    { name: "p4" },
  ],
  [
    { name: "p2" },
    { name: "p3" },
    { name: "p1" },
    { name: "p9" },
    { name: "p6" },
  ],
];
const findObj = [{ name: "p1" }, { name: "p2" }, { name: "p6" }];
const set = new Set(findObj.map((o) => o.name));

const result = items.filter((arr) => {
  const remain = arr.reduce((acc, curr) => {
    if (set.has(curr.name)) acc.add(curr.name);
    return acc;
  }, new Set());
  return remain.size === set.size;
});
console.log(result);

Answer №2

const elements = [[{name:"p2"},{name:"p3"}, {name:"p7"},{name:"p9"},{name:"p1"}],[{name:"p6"}, {name:"p3"},{name:"p7"}, {name:"p9"},{name:"p2"}],[{name:"p3"},{name:"p6"}, {name:"p7"},{name:"p9"},{name:"p4"}],[{name:"p2"}, {name:"p3"},{name:"p1"}, {name:"p9"},{name:"p6"]]

const searchValues = [{name:"p1"},{name:"p2"},{name:"p6"}]


const results = elements.filter(item=>{
  const itemsArr = item.map(childItem=>childItem.name);
  let allFound=true;
  searchValues.forEach(obj=>{
  if(!itemsArr.includes(obj.name)){
  allFound=false;
  }
  })
  return allFound;
})
console.log(results)

Answer №3

To extract all names from each item in an array using filter and map, you can use .map(prop=>prop.name) or a simpler method with destructuring like .map(({name})=>name. Then, filter the items based on whether their names are included in findObj.

const items = [[{name:"p2"},{name:"p3"}, {name:"p7"},{name:"p9"},{name:"p1"}],[{name:"p6"}, {name:"p3"},{name:"p7"}, {name:"p9"},{name:"p2"}],[{name:"p3"},{name:"p6"}, {name:"p7"},{name:"p9"},{name:"p4"}],[{name:"p2"}, {name:"p3"},{name:"p1"}, {name:"p9"},{name:"p6"}]]

const findObj = [{name:"p1"},{name:"p2"},{name:"p6"}]
const result = items.filter(item=>{
    const arrProp  = item.map(prop=>prop.name)
    const filtProp = findObj.map(({name})=>name)
    return filtProp.every(x=>arrProp.includes(x));
})
console.log(result)

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

The straightforward onclick action only functioned once

Looking for assistance: Can someone explain why this code snippet isn't functioning properly? It seems that the increment is only happening once. var player = document.getElementById("player"); var button = document.getElementById("button"); functio ...

What could be causing replace() to malfunction in Node.js?

I am dealing with some data in Node.js and I am trying to replace the ampersands with their escape key. Below is the code snippet I am using: let newValue = data; for (label in labelData.data) { let key = "Label " + label; newValue = newValue.rep ...

An object is not defined in the following scenario

I currently have a custom function that includes the following code snippet: 1: var object = get_resource($scope, CbgenRestangular, $stateParams.scheme_id); 2: console.log(object) This function triggers the following code: get_resource = function ($sc ...

Unveiling and Shifting Among Concealed HTML Forms

After going through numerous tickets with similar questions, I still can't seem to achieve what I want. So, I have no choice but to ask this question myself. I currently have an HTML page with 2 forms and 2 buttons. Both forms are initially hidden us ...

Getting directions using the node-googlemaps module in node.js can be achieved by following these steps

For the past day, I've been attempting to make progress with this Node.js Google Maps directions example, but so far, no success. Every time I run it, I keep seeing ·· √ OK » 2 honored (0.848s). I've previously asked a similar question on U ...

Combine functions from two objects that share the same properties into an array for each property

I need help combining the methods from two objects into one, resulting in an array of methods for each property in the parent object: obj1 = {"prop1":"method1","prop2":"method2"} obj2 = {"prop1":"method3","prop2":"method4"} Expected result: obj1 = {"pro ...

Issue with Firefox causing Bootstrap form to appear incorrectly

I recently created a customized form using Bootstrap, but unfortunately, I'm encountering an issue with Firefox. Despite functioning perfectly on other browsers, the radio buttons are being pushed off the edge of the page and aren't displaying pr ...

Utilize the power of Jolt to seamlessly transform and convert straightforward flat JSON data into intricate nested JSON

Looking for help with transforming flat json data into nested json using jolt. I'm new to jolt and here is the input I'm working with: { "id": "LIKKI MOSORU", "aff_id": "WOOD", "aff_name": "WOOD-LOVE", "aff_desc": "WOOD INC.", "aff_corrltn_ ...

Ways to update an angular page using the router without resorting to window.location.reload

I have a specific method for resetting values in a component page. The process involves navigating from the "new-edition" page to the "my-editions" component and then returning to the original location at "new-edition". I am currently using this approach ...

Eliminating an element from an array depending on the value of its properties

I need to remove an object from my List array by matching its properties value with the event target ID. Currently, I am using findIndex method to locate the index ID that matches the event.target.id. Below is an example of one of the objects in my list a ...

How do I incorporate an external template in Mustache.js?

Welcome, I am a beginner in using Mustache.js. Below is the template and JS code that I have: var template = $('#pageTpl').html(); var html = Mustache.to_html(template, data); $('#sampleArea').html(html); Here is the template ...

Display loading spinner and lock the page while a request is being processed via AJAX

Currently, I am working on a project using MVC in C#, along with Bootstrap and FontAwesome. The main objective of my project is to display a spinner and disable the page while waiting for an ajax request. Up until now, I have been able to achieve this go ...

Setting the CSS position to fixed for a dynamically generated canvas using JavaScript

My goal is to fix the position style of the canvas using JavaScript in order to eliminate scroll bars. Interestingly, I can easily change the style using Chrome Inspector with no issues, but when it comes to implementing it through JS, I face difficulties. ...

How can I run JavaScript code written in the Chrome console on standalone Node.js platform

After successfully creating a script that functions when input into the Google Chrome developer console, I now desire to convert it into an executable file. My goal is to open the file and have it log all activity in a separate node.js console window, whil ...

What is the best way to utilize ng-if in the index.html page depending on the URL?

Is there a way to hide certain elements in the index page based on the URL of nested views? In my index.html file, I am looking to implement something like this: <top-bar ng-if="!home"></top-bar> <ui-view class="reveal-animation"> ...

"Utilize Vue i18n to properly display currency amounts in USD

Whenever I present my currency as USD, it always shows up like this: USD$500.00. I am attempting to eliminate the USD prefix from the beginning. Below is my numberFormats configuration: numberFormats: { 'en': { currency: { ...

How can I combine an ordinary image and a CSS2D image in THREE.js CSS2DRenderer and save them together as a single .jpg file?

After implementing the following code... (1) I successfully saved regular rendered THREE.js scenes as .jpg files; (2) Additionally, I managed to utilize CSS2DRenderer to display CSS2D labels on top of the canvas; (3) Now, my goal is to save the image wi ...

What is the process of defining a route for a JSON response in an Express application?

I've been following an Angular tutorial on handling form submissions with promises, which I found here. My server is running on Node and I'm using Express to manage routes. However, when I submit the form and reach the line var $promise = $http. ...

Create a stunning MUI App bar with a blurred effect below a fixed Navbar

Is there a method to apply a blur effect to the background of my material-ui AppBar component, creating a visually appealing overlay below the fixed navbar? I have experimented with using filter: blur(0) but it does not achieve the desired result. I am lo ...

Utilizing Angular's ng-repeat directive to dynamically generate images, with the added functionality of attempting to

I am utilizing angular-drupal to fetch data from my backend built on Drupal. My objective is to create an image gallery using the default endpoints provided by the services module. I make a call to node load to retrieve a specific node, then I extract the ...