Discovering ways to fetch an array of objects using object and arrays in JavaScript

When comparing an array of objects with a single object and listing the arrays in JavaScript, specific conditions need to be met to retrieve the array of objects:

  1. If the itemvalue and idvalue are the same, check if the arrobj cid has the same codevalue and return both array of objects.

  2. If the itemvalue and idvalue are the same, check for mismatching cid in the arraylist and a codevalue that does not exist in the arraylist, then return the array of objects.

  3. If the itemvalue and idvalue are the same, check if the codevalue matches in the arraylist and the cid has a value that does not exist in the arraylist, return the array of objects.

If none of the above conditions are met, return an empty array []

//data1
var arraylist = ["IN","FP", "FN"];
var arrobj1 = [
  {id:1, name: "sun", cid: "IN", itemvalue: "3456"},
  {id:2, name: "mon", cid: "FI", itemvalue: "4567"},
  {id:3, name: "tues", cid: "SP", itemvalue: "4567"},
  {id:4, name: "thurs", cid: "FI", itemvalue: "2345"},
]
var obj1 = { id:5, name: "ben", codevalue: "SG", idvalue:"4567"};

Expected Output:
[
{id:2, name: "mon", cid: "FI", itemvalue: "4567"},  
{id:3, name: "tues", cid: "SP", itemvalue: "4567"}
]

//data2
var larrylist= ["IN","FI","FR"];
var arrobj2 = [
  {id:1, name: "sun", cid: "IN", itemvalue: "1234"},
  {id:2, name: "mon", cid: "FI", itemvalue: "2468"},
  {id:3, name: "tues", cid: "IN", itemvalue: "2468"},
  {id:4, name: "thur", cid: "FI", itemvalue: "2345"},
]
var obj2 = { id:5, name: "ben", codevalue: "SP", idvalue:"2468"};

Expected Output:
[]

//data3
var arraylist= ["IN","FI","FR"];
var arrobj3 = [
  {id:1, name: "sun", cid: "IN", itemvalue: "1234"},
  {id:2, name: "mon", cid: "FI", itemvalue: "2468"},
  {id:3, name: "tues", cid: "SG", itemvalue: "2468"},
  {id:4, name: "thur", cid: "FI", itemvalue: "2345"},
]
var obj3 = { id:5, name: "ben", codevalue: "FI", idvalue:"2468"};

Expected Output:
[
 {id:2, name: "mon", cid: "FI", itemvalue: "2468"}
]

Tried:

const result = arrobj1.filter((item) => {
  return item.itemvalue === obj.idvalue &&
    (
      !arraylist.includes(item.cid)
      || item.cid === obj.codevalue
    )
})

Answer №1

Being clear and specific when stating a problem often leads to finding a solution more easily. Make sure to articulate your thoughts precisely, and then code exactly what you have described.

By applying this approach to the original poster's issue and providing examples, we can derive the following:

The objective is to filter an array of objects (arrobj1) in order to generate another array that meets specific criteria related to an object (obj1) and another array (arraylist).

  1. The filtering condition is met if there is a match between the property idvalue of obj1 and the property itemvalue of the array element, AND...

  2. In addition, the condition must (2a) identify a match between the property codevalue of obj1 and the property cid of the array element, BUT (2b) this comparison depends on whether either the element's property (cid) or the object's property (codevalue) is present in arraylist. Specifically, if either the element's cid or the object's codevalue is in the arraylist, then the element's cid value must match the codevalue of obj1.

Framing the problem with such precision makes coding the conditions much simpler. Let's break it down into manageable pieces...

// condition 1
// el represents an element from arrobj1, obj is a similar instance to obj1
// check for equality between their itemvalue and idvalue properties
const idsMatch = (el, obj) => obj.idvalue === el.itemvalue;

// condition 2b
// el denotes an element from arrobj1, obj is akin to obj1, and cidList 
// is the list of cids provided (similar to arraylist)
// verify if the element's cid and obj's codevalue are included in the cidList
const cidFound = (el, obj, cidList) => {
  return cidList.includes(el.cid) || cidList.includes(obj.codevalue);
}

// condition 2a
// el is taken from arrobj1, obj resembles obj1
// assess whether their cid and codevalue properties match
const cidPropMatch = (el, obj) => obj.codevalue === el.cid;

// combine from 2a and 2b to create condition 2
// cidsMatch holds true if the element isn't in the cidList, or if it is and the objects' properties match
const cidsMatch = (el, obj, cidList) => {
  return !cidFound(el, obj, cidList) || cidPropMatch(el, obj);
}

// consolidate into a predicate
const filterPredicate = (el, obj, cidList) => {
  return idsMatch(el, obj) && cidsMatch(el, obj, cidList);
};

And there you have it! A demonstration...

// condition 1
const idsMatch = (el, obj) => obj.idvalue === el.itemvalue;

// condition 2b
const cidFound = (el, obj, cidList) => {
  return cidList.includes(el.cid) || cidList.includes(obj.codevalue);
}
// condition 2a
const cidPropMatch = (el, obj) => obj.codevalue === el.cid;

// condition 2
const cidsMatch = (el, obj, cidList) => {
  return !cidFound(el, obj, cidList) || cidPropMatch(el, obj);
}

// predicate
const filterPredicate = (el, obj, cidList) => {
  return idsMatch(el, obj) && cidsMatch(el, obj, cidList);
};

var arraylist = ["IN","FP", "FN"];
var arrobj1 = [
  {id:1, name: "sun", cid: "IN", itemvalue: "3456"},
  {id:2, name: "mon", cid: "FI", itemvalue: "4567"},
  {id:3, name: "tues", cid: "SP", itemvalue: "4567"},
  {id:4, name: "thurs", cid: "FI", itemvalue: "2345"},
]
var obj1 = { id:5, name: "ben", codevalue: "SG", idvalue:"4567"}

const result = arrobj1.filter(el => filterPredicate(el, obj1, arraylist));
console.log(result);

// Expected Output
// [
// {id:2, name: "mon", cid: "FI", itemvalue: "4567"},  
// {id:3, name: "tues", cid: "SP", itemvalue: "4567"}
// ]


arraylist = ["IN","FI","FR"];
var arrobj2 = [
  {id:1, name: "sun", cid: "IN", itemvalue: "1234"},
  {id:2, name: "mon", cid: "FI", itemvalue: "2468"},
  {id:3, name: "tues", cid: "IN", itemvalue: "2468"},
  {id:4, name: "thur", cid: "FI", itemvalue: "2345"},
]
var obj2 = { id:5, name: "ben", codevalue: "SP", idvalue:"2468"}

const result2 = arrobj2.filter(el => filterPredicate(el, obj2, arraylist));
console.log(result2);

// Expected Output
// []


arraylist = ["IN","FI","FR"];
var arrobj3 = [
  {id:1, name: "sun", cid: "IN", itemvalue: "1234"},
  {id:2, name: "mon", cid: "FI", itemvalue: "2468"},
  {id:3, name: "tues", cid: "SG", itemvalue: "2468"},
  {id:4, name: "thur", cid: "FI", itemvalue: "2345"},
]
var obj3 = { id:5, name: "ben", codevalue: "FI", idvalue:"2468"}

const result3 = arrobj3.filter(el => filterPredicate(el, obj3, arraylist));
console.log(result3);

// Expected Output
// [
//  {id:2, name: "mon", cid: "FI", itemvalue: "2468"}
// ]

The crux lies in the meticulousness of defining and coding each step. By being precise about what you intend to achieve, you increase the chances of success. In this case, the accurate articulation of the requirements led to the expected results without any issues.

Answer №2

Here is a possible solution for your request:

let filteredResult = data.filter((element) =>
    element.value === myObject.id && (listOfIds.includes(element.cid) || element.cid === myObject.code)
);

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

Common mistakes encountered when utilizing webpack for react development

I'm currently following the exercises in Pro MERN Stack by Apress and have come across a webpack issue. Everything was running smoothly until I introduced webpack into the mix. Now, when I execute npm run compile, I encounter the following error: > ...

Find the mean of two values entered by the user using JavaScript

I'm sorry for asking such a basic question, but I've been struggling to get this code to work for quite some time now. I'm ashamed to admit how long I've spent trying to figure it out and how many related StackOverflow questions I ...

Do you know the method to make a Youtube iframe go fullscreen?

I am encountering an issue with developing an iframe where I am unable to make it go fullscreen from within the iframe. Fullscreen API works when both the iframe and hosting website are on the same domain, as well as triggering fullscreen from outside the ...

Unit testing the error function within the subscribe method in Angular

I've been working on a unit test for the subscribe call, but I'm struggling to cover the error handling aspect of the subscribe method. The handleError function deals with statusCode=403 errors and other status codes. Any assistance would be grea ...

Can JavaScript be used to continuously monitor a window variable object in real-time?

Is there a way to dynamically control a variable in JavaScript? I'm currently working on a code that needs to display a button when it reaches the last signature of an automatic request process. The code for activating/deactivating the button is show ...

The compatibility issue between jQuery Tabs and Sliding effect

Hey there, I'm currently working on a website that requires a vertical tab system. I also have an arrow image that shows which tab or thumbnail the user has selected, and it should smoothly slide between the two thumbnails. You can check out the pro ...

Error: Attempting to access 'map' property of an undefined variable in NEXTJS

I've been struggling to retrieve an image from this API using getStaticProps, but for some reason I can't seem to make it work. In my code snippet, if I add a question mark like this, the console returns 'undefined'. What could be caus ...

Updating and adding information in a JSON file using PHP functionality

I have a function to control and update data in a post. However, I am encountering an issue where the function both updates existing information and adds duplicate information during the second addition. Can anyone assist me in identifying where the mista ...

Troubleshooting issues with cross-domain jQuery ajax requests

Struggling with this code and unable to make it work. This call consistently returns a "Failed to load resource: the server responded with a status of 401 (Unauthorized)" error message. $('#btnZendesk').click(function () { $.ajax({ ...

Tips on submitting an Array from a Textarea to mongoDB

I have a question regarding posting an array of serial numbers. When I try to post the serial numbers added in the textarea, they are posted as a single string. Here is my form: <form class="" id="serialsForm" action="/serialsnew" method="post"> &l ...

Regarding passing input into a JavaScript class method that is exported through the exports keyword

The inquiry at hand relates to ExtendScript code, however, I believe it should be independent of any specific javascript implementation. If we have the following in a JS library file (base64.js) exports.encode64 = encoder('+/'); //... function ...

Unable to access Vue.js cookies: they are not defined

I integrated vue-cookies into my project successfully. In the main.js file, I added the following code: createApp(App) .use(store) .use(router, axios, VueCookies) The script section in App.vue file looks like this: <script> import Navbar fr ...

Getting the WebElement object by manually clicking an element while in an active WebDriver Session

I am currently developing a Java Swing application for managing object repositories in Selenium scripts. This application will launch a WebDriver instance and allow users to manually navigate to the desired element for inspection. My goal is to capture th ...

Retrieve the key{index} property from the .map method in React for the element that was just clicked

I am facing an issue with my code const Component = () => { const [Clicked, setClicked] = useState(false); const handleClick = (prop, e) => { console.log(prop); } return ( <div> {arrayCard.map((item, i) => { ...

Exploring AngularJS: Effiecient Looping and Styling

Being a beginner in AngularJS, please excuse me if this question seems silly. I want to display my data in a grid format (using Ionic) where each row has separate columns like this: <div class="row"> <div class="col-33">Item 1</div> ...

Can anyone provide a solution for determining the number of active intervals in Javascript?

Similar Question: How to View All Timeouts and Intervals in JavaScript? I've been working on an HTML5 game that includes a lot of graphical effects using intervals created by the setInterval function. However, I've noticed that my game is ru ...

Display a spinning wheel or progress bar while the website is in the process of loading

Looking to construct a treeview using the jquery-treeview plugin but noticing it's quite time-consuming (about 5-7 seconds). I'm interested in adding a spinning wheel or progress bar to indicate loading while the page is processing. Any suggestio ...

Converting numbers in React Native, leaving only the last four digits untouched

When mapping biomatricData.ninId, the value I am receiving is "43445567665". biomatricData.ninId = 43445567665 My task now is to display only the last 4 digits and replace the rest with "*". I need to format 43445567665 as follows: Like - *******7665 ...

Having difficulty sending emails with attachments using AngularJS

While using Angular, I encountered an issue when sending an email with an attachment. The response I received contained the data code of the file instead of its actual format. See example: https://i.stack.imgur.com/vk7X8.png I am unsure what is causing t ...

What is the process of directing to another HTML page within the same Express controller script?

I am looking to switch the initial page (login page) to a second page (admin dashboard) from within the same controller in Express after a specific action has been taken. Here is the relevant code snippet from my controller file nimda.js: function handle ...