Sophisticated filtration mechanism involving two entities and a binary condition

I have an array called burgerActions :

[
  {
    statusId: 2,
    label: 'Accept'
  },
  {
    statusId: 3,
    label: 'Reject'
  },
  {
    label: 'Consult'
  },
  {
    label: 'Transfer'
  }
]

and also this object named status which can be either :

{
  "label": "Accept",
  "id": 2
}

or :

{
  "label": "Reject",
  "id": 3
}

In the first scenario, a new array needs to be created from the burgerActions array where the statusId does not match the id of the status object provided (we have only one status object from the two cases listed). To achieve this, the filter method is utilized :

const result =  burgerActions.filter((element) => {
  return element.statusId !== recommendation.status.id
})

In the second scenario, a more complex condition needs to be applied alongside using boolean values

const statusRef = recommendation.recipient

In the first situation, I need to filter out the last object in the burgerAction array ({label: 'Transfer'}) if statusRef is false, but not when it's true. A method that accomplishes this type of filtering without direct if () conditions is required due to multiple scenarios being present.

Answer №1

If you're looking to sort out the items that don't match the statusId from the recommendation.status.id and if

recommendation.recipient === true
, then filter out those without a statusId, you can implement this condition in the filtering callback function:

element.statusId !== recommendation.status.id && recommendation.recipient ? element.statusId != null : true;

The logic behind

&& recommendation.recipient ? element.statusId != null : true
is to filter elements with a statusId only if recommendation.recipient is set to true.

Here's how your code should look like:

var recommendation = {
  status: {
    "label": "Pending",
    "id": 1
  },
  recipient: true
};

const result = burgerActions.filter((element) => {
  return element.statusId !== recommendation.status.id && recommendation.recipient ? element.statusId != null : true;
});

Demo:

var burgerActions = [{
    statusId: 2,
    label: 'Accept'
  },
  {
    statusId: 3,
    label: 'Reject'
  },
  {
    label: 'Consult'
  },
  {
    statusId: 1,
    label: 'Transfer'
  }
];

var recommendation = {
  status: {
    "label": "Pending",
    "id": 1
  },
  recipient: true
};

const result = burgerActions.filter((element) => {
  return element.statusId !== recommendation.status.id && recommendation.recipient ? element.statusId != null : true;
});

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

What are the benefits of using `observer` over `inject` when passing data to a React component in MobX?

After reading MobX documentation, it appears that using observer on all components is recommended. However, I have discovered that by utilizing the inject method, I am able to achieve more precise control over which data triggers a re-render of my componen ...

Mastering the art of nesting loops for optimal efficiency

I’m facing a challenge with my code as it seems to be skipping all the if statements and displaying “invalid” instead. The scenario involves a 2D array representing a movie theater with different seat prices. The user is required to input an amount o ...

How can you determine the number of elements that match in two arrays?

As a coding newbie, I'm looking to create a JavaScript function that compares two arrays and assigns a score based on the number of matching elements. However, when I attempt to run it in Chrome's console, I receive an error message stating that ...

Verify whether a dependency is being passed into an Angular component

As mentioned in a discussion about IE caching issues, Internet Explorer tends to cache things when using ajax with AngularJS, causing potential problems. You can find a helpful solution to this problem here. Given that we have multiple angular apps on our ...

Unlock the Potential of Spring REST-JWT-JavaScript for Seamless Transitions

In my Java Spring REST back-end, I am implementing a security feature using Json Web Tokens instead of sessions. For the front-end, I plan to use JavaScript and jQuery for sending requests to the back-end, along with HTML. After a successful login, I stor ...

Transmit information from the backend Node.js to the frontend (without using sockets)

Is there a method to transfer data from my socket, for example example.com:8000, to my web server that is not on the same socket at example.com/index.php? I've searched through various codes but have not come across any solutions yet. If you could pro ...

Searching dynamically using class names with JQuery

I am seeking to create a dynamic search input based on the class names within the span tags. However, I am struggling with displaying the class name that I have identified. My goal is to show the class names that match the entered value in the input on the ...

Pass information from JavaScript to PHP without using a form

I am trying to pass data from JavaScript to PHP without using an HTML form. The scenario involves the user clicking on a specific HTML div, sending its ID to a JavaScript file, and then transferring it back to a PHP file. How can I achieve this? Below is ...

Showing a series of text entries one after the other, each appearing with a smooth fade-in and fade-out

I am eager to showcase a list of text in a sequential order, implementing a fade-in/fade-out effect and concluding with the display of an image. Additionally, I aim to have all the text centered on the page. <div>a<div> <div>b</div> ...

Using table.column as a function in jQuery datatabbe is not supported

When using jquery datatable, I encountered an error stating "table.column is not a function." <script> $(document).ready(function() { var table = $('#lsotable').dataTable(); $("#lsotable thead th").each( function ( i ) { ...

The signup controller encountered a malfunction with illegal arguments: an undefined value and a string

I recently started learning MERN through a tutorial and encountered an issue with my database. I have successfully created a function to send data to the database, but for some reason, I can't see the data in the database. Below is the code snippet: ...

Error: Unable to establish connection with local host (::1) on port 50106

I am currently in the process of developing a Discord bot using Node.js and erela.js. However, I encountered an error when attempting to retrieve the server that handles erela: A node error occurred: connect ECONNREFUSED ::1:50106 2020-05-01T21:23:19.367 ...

AngularJS is experiencing delays when processing subsequent $http delete requests, leaving them stuck in a

I am currently working on a project where I have a table displaying a list of objects, with each object having multiple child objects associated with it. The technologies I am using include Angular 1.2.20, Express 4.6.1, and Node 0.10.25. In the table, the ...

Looking for a Plugin that Can Responsively Display Images in a Vertical Layout - Does One Exist using Jquery

Looking for a gallery slider plugin that is responsive both horizontally and vertically. Have tried Flexslider1/2, Galleria, and others but they do not adjust to vertical resizing. Changing the CSS did not help. If you resize the browser horizontally with ...

The Hidden Power of jQuery: Unleashing the Full Potential of .text()

I'm trying to make two values equal, but it's not working... var rowID = $("#@idSelectObjectGuid").val(); $($(".ls-grid-body tr").children("<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="240a64524770454648410a74564d ...

Utilize AngularJS to integrate a service into the router functionality

What is the best way to inject a service into my router so that its JSON result will be accessible throughout the entire application? Router: export default ['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterP ...

Arranging a Multi-layered Array Based on One of Its Values

Before anything else, I have reviewed and attempted the following links: Sort Multi-dimensional Array by Value Sort Multi-dimensional Array by Value Sort php multidimensional array by sub-value http://php.net/manual/fr/function.array-multisort.php. No ...

Replace specific text with a span element around it?

I am working with the following HTML code: <p class="get">This is some content.</p>. My goal is to modify it so that it looks like this: <p class="get">This is <span>some</span> content.</p>. To achieve this, I have ...

displaying a multi-dimensional array with the same key value in PHP

I need assistance with printing the first_name and last_name together from an array named $users. Array ( [first_name] => Array ( [0] => John [1] => Tom ) [last_name] => Array ( ...

what strategies can be implemented to prioritize addressing validation errors in return forms

I'm currently working on a web application in asp.net mvc-5, and I have a contact form displayed in the middle of the Contact Us view. Here's the code snippet: <div class="col-sm-8 col-sm-push-4"> <h2>Contact Us1 ...