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 partial template is not functioning as anticipated

Introducing an interface designed to accept two templates, with the resulting function being a partial of one of them (similar to React-Redux): export type IState<TState, TOwnProps> = { connect: (mapStateToProps: MapStateToProps<TState, Parti ...

Invoke the function defined within a modal when dismissing a ui-bootstrap modal

Inside my ui-bootstrap modal controller, I have a $watch function set up for a variable. The code snippet looks like this: main.controller('modalCtrl', ['$scope', '$rootScope', '$modalInstance', function ($sc ...

Updating Angular Material theme variables during the build processIs this okay?

How can I easily customize the primary color of my angular 6 application to be different for development and production builds? Is there a simple solution to automatically change the primary color based on the build? ...

Discover the magic of observing prop changes in Vue Composition API / Vue 3!

Exploring the Vue Composition API RFC Reference site, it's easy to find various uses of the watch module, but there is a lack of examples on how to watch component props. This crucial information is not highlighted on the main page of Vue Composition ...

Loading external libraries in Angular2: A step-by-step guide

I'm currently working on incorporating a Datepicker in Angular 2, but I'm facing an issue where the library is not loading. This is causing a template parsing error stating 'material-datepicker' is not a recognized element: My System.c ...

I am unable to implement code coverage for Cypress in Debian at the moment

Having trouble obtaining code coverage results using Cypress in my Virtual Machine (Debian Bullseye), but no issues when I run the same project on my Windows machine. On Linux, the code coverage shows up as: Click here to view Index.html inside lcov-repor ...

Ensuring that the empty bubble remains undisturbed, here's a guide on effectively implementing the if

I need assistance with adding an "if condition" to my text field. The condition should prevent the empty bubble from appearing when the send button is clicked. function verifyInput(){ var currentText = document.getElementById("demo").innerHTML; var x ...

What causes Chrome Extension Images to appear broken when they are inserted into the DOM?

Currently working on a Chrome extension, I am attempting to insert a div with a background image into the DOM using a content script. The CSS is loading correctly, and upon inspecting the Developer Tools, the image URL appears to be correct. $('.clos ...

What is the best way to transfer an element and all its children to another div without losing any jQuery functionality?

At first, sharing an example of the JavaScript and HTML from my page is challenging because I couldn't make it work on JSfiddle. The issue I'm facing involves jQuery on a page where I've created two tabs. Essentially, it's the same con ...

Activating a certain class to prompt a drop-down action

My PHP code is displaying data from my database, but there's a bug where both dropdown menus appear when I click the gear icon. I want only one dropdown to appear when clicking the gear of a specific project. Can you help me fix this issue? It's ...

Differences between encoding URL variables in HREF and using JS window.location for onclick events

For some reason, this particular hyperlink is not functioning properly. I have a Javascript redirect (window.opener.location) where I pass several variables through the URL. The problem arises when these variables contain apostrophes. In PHP, I am using UR ...

Transforming a JSON object property value from an array into a string using JavaScript

I am facing an issue with an API call I am using, as it is sending objects with a single property that contains an array value (seen in the keys property in the response below). However, I need to work with nested arrays in order to utilize the outputted v ...

The straightforward use of XMLHttpRequest to retrieve the response xhttp.responseText is not functioning properly

I am facing an issue where this.responseText is not returning the content of the file. Can someone assist me in solving this problem? Thank you. Console.log also does not return the content of the file. function loadMegaContent() { var xhttp = new XMLHtt ...

Encountered a discrepancy with npm dependencies during the update or installation process on a legacy project

I am encountering issues while attempting to run an older project. Every time I try to npm install or start the project, it throws various dependency errors, particularly related to the outdated npm version. My current node version is 16.x, whereas the pro ...

Incorporating an SVG with CSS styling from a stylesheet

After exploring various articles and questions on the topic, I am yet to find a definitive solution. I have an external file named icon.svg, and my objective is to utilize it across multiple HTML files with different fill colors and sizes for each instanc ...

determining the overall page displacement

I'm working with this code and I need help using the IF condition to check if the total page offset is greater-than 75%. How can I implement that here? function getLocalCoords(elem, ev) { var ox = 0, oy = 0; var first; var pageX, pageY; ...

creating a JSON object in PHP that can be easily parsed by JavaScript

In my project, I have an extensive list of items, each item further divided into four sub-items. While it's convenient for me to organize this data in nested arrays using PHP, I encounter issues when trying to transfer them as a JSON object to the cli ...

Create a variable and set it equal to the value of a form

I'm having trouble setting a value to a hidden form field that needs to come from a query string parameter. The function that extracts the query string parameter is working properly, but the function that assigns this variable to the hidden form field ...

Enhancing Values Across a Timeframe Using JavaScript

Last time, I asked about my code. Here is what I have currently: var secs = 100; setInterval(function() { var $badge = $('#nhb_01'); $badge.text((parseFloat($badge.text())+0.01).toFixed(2)); }, secs); I want the counter to increase by ...

Ways to transfer information from an axios API to a state in React

I am currently working with an API that consists of an array of objects. My goal is to pass this data into a state in order to display it within a component on a website. First Approach: // Fetches the API data const newData = axios.get(url).then( ...