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

What is the method behind the magic of `print(*range(*b'e'))` counting from 0 to 100?

Could someone provide insight into the process by which this code generates numbers from 0 to 100? [Code] print(*range(*b'e')) [Result] 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 3 ...

Leverage promises to alter reactive data, strategically placing them to minimize the frequency of triggers being activated

Initial Method const list = reactive([1, 2, 3, 4, 5]); const clickHandler = () =>{ list.push(...[11, 12, 13, 14, 15]); list.push(...[16, 17, 18, 19, 20]); Promise.resolve().then(() => { list.push(33) ...

Display the matrix in a semi-spiral pattern

I am working with a 3 by 5 matrix, filled with numbers from 1, presented as follows: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 The task is to print the values in a half-spiral order, starting from the bottom left vertically: 11 6 1 5 10 15 12 7 2 4 9 ...

React Checkbox Sum Component - Effortlessly Improve User Experience

Looking for assistance with passing checkbox values to a React component in my app. I'm currently implementing a food list display using JSON data, but I'm unsure how to transfer the checkbox values to another component. For reference, here&apos ...

Is there a way to search for the keyword "/test/" within a lengthy string using Regular Expressions?

When faced with a string structured like this: const myString = /example/category/modify?itemID=someID&type=number How can I efficiently extract the segment "/category/" by employing: const subSegment = myString.match(...); My framework of choice i ...

Filtering a list in AngularJS based on a property of an object with a filter applied on it

I am facing an issue with filtering a list of objects based on their properties using the filter filter. The problem arises when certain object properties have filters applied to them that alter their displayed format (such as the formatDate filter in the ...

Enhance your user interface by adding a tooltip above a button

I am currently working on creating a button that can copy content from a variable into the clipboard using TypeScript and Material-UI. Here is what I have tried: const [copySuccess, setCopySuccess] = useState(''); const copyToClipBoard = async ( ...

Toggling event triggers with the second invocation

At this moment, there exists a specific module/view definition in the code: define(['jquery', 'underscore', 'backbone', 'text!templates/product.html'], function($, _, Backbone, productTemplate) { var ProductView = ...

Could someone help clarify this issue within a React project?

I've encountered an issue with a react task and I could use some clarification. // React is loaded and is available as React and ReactDOM // imports should NOT be used class Input extends React.PureComponent { render() { let {forwardedRef, ...ot ...

Tips for designing a customizable color scheme for your website

Are you looking to implement a changeable color scheme for your website? Getting started can be daunting, especially if you're unfamiliar with sass. Would appreciate it if anyone could share some helpful tutorials or links? For example: example ...

Can a custom javascript object be exported in various formats similar to the Date object?

Consider the following scenario where I have a custom object: function MyObject(a, b){ this.prop = a; this.name = b; this.doSomething = function(){ return "something"; } } var a = new MyObject(4, 'name'); I am looking fo ...

Click once to reveal, click twice to conceal the slider

I currently have a web page set up so that a single click on the text displays a slider for selecting a range of values. Now, I want to incorporate a feature where a double click will remove the slider. Below is the HTML code: <!DOCTYPE html> < ...

Passing data between Vue.js components effortlessly without relying on events

At the moment, I am utilizing Laravel Nova. It's worth noting that it operates using vue.js. I've created a personalized vue component which requires the ability to modify data inside another component. This specific component is located in the ...

Struggling to incorporate jquery and jquery-ujs into Browserify, encountering an error stating Uncaught ReferenceError: jQuery is not defined

I am currently working on a Ruby on Rails project and utilizing Browserify to manage my JavaScript dependencies. However, I keep encountering an error message stating "Uncaught ReferenceError: jQuery is not defined" because jquery-ujs is attempting to call ...

Tips for incorporating a svg file into your React project

I am facing an issue with my custom React, Typescript, and Webpack project. I am trying to import a basic .svg file and utilize it in one of my components. However, Typescript is throwing the following error: Cannot find module I have tried installing s ...

How can you toggle the visibility of a div based on detecting a specific class while scrolling?

My webpage features a sticky header that gains an extra .header-scrolled class when users scroll down. I am looking to switch the logo displayed in the header once it has been scrolled. Below is a simplified version of my HTML code: <header class=".he ...

Issues with Node.js routes on the express server aren't functioning as expected

I used to have a node.js express server up and running on my previous server. However, after migrating to a new server, the code seems to have stopped functioning. Let me share the setup of my server: var fs = require('fs'); var express = requi ...

Issue with API/CORS not fetching while utilizing react-email in ASP.NET/React.JS application

My React App is running at port 44411 and react-email is running at port 3000. I followed a tutorial on setting up react-email, but it didn't work initially. After some troubleshooting, I managed to make my API request go through Postman. The next st ...

Stopping setTimeout when leaving the current page: Is it possible?

Good evening, I am looking for advice on how to cancel a setTimeout function when a user navigates to other pages (for example, by clicking other links or pressing the back button in the browser, but not by changing tabs). I have attempted to use the windo ...

Having trouble accessing jQuery function within WordPress

Why is there a ReferenceError: Error message that says "manualEntry is not defined," appearing while trying to use the code snippet below in a Wordpress environment? <a href="#" onclick="manualEntry()">hide</a> <script ...