JavaScript Filter Function: filtering based on multiple conditions (either one can evaluate to true)

I seem to be missing something very simple here.

I am working with an array of objects that contains various information. Depending on user interaction, I want to filter out certain objects;

let arr = [
 {'num': 1, 'name': 'joe'},
 {'num': 2, 'name': 'jane'},
 {'num': 3, 'name': 'john'},
 {'num': 3, 'name': 'johnny'},
]

This is what I have attempted so far:

 function filterArr(arr) {
  return arr.filter(obj => {
    if(obj.num && obj.num !== 1) {
      return obj;
    }
    if(obj.num && obj.num !== 3) {
     return obj;
    }
  })
}

After running the filterArr function, I receive the original array back instead of just {'num': 2, 'name': 'jane'},, as expected. I have added console.log statements inside both nested conditions.

I would appreciate any assistance with filtering the array based on one of two conditions being true.

Answer №1

Each and every num will satisfy one of your if conditions because it is impossible for a number to be equal to both 1 and 3 simultaneously**. You can easily string together the && condition within the filter function to validate all numbers:

let arr = [
 {'num': 1, 'name': 'joe'},
 {'num': 2, 'name': 'jane'},
 {'num': 3, 'name': 'john'},
 {'num': 3, 'name': 'johnny'},
]

let filtered = arr.filter(a => a.num && a.num !== 3 && a.num !== 1)

console.log(filtered)

(**Unless it's 0, null, undefined or any other falsy value. In these cases, they will not meet the requirements set by the obj.num condition in either if statement)

Answer №2

First things first, let's analyze the issue at hand.

You encountered a situation where you had two conditions; one checking for inequality to 1, and the other checking for inequality to 3. For instance, if num = 1, the first condition fails but the second one succeeds, leading to the return of true in all cases.

The solution is to combine both conditions into a single if statement.

let arr = [{'num': 1, 'name': 'joe'},{'num': 2, 'name': 'jane'},{'num': 3, 'name': 'john'},{'num': 3, 'name': 'johnny'},]

function filterArr(arr) {
  return arr.filter(obj => obj.num !== 1 && obj.num!=3)
}

console.log(filterArr(arr))

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

Utilizing array iteration to display images

I am having trouble getting the images to display on my card component. The description appears fine, but the images are not rendering properly even though I have the image data in an array. Here is the Card Component code: export const Card = (props) =&g ...

Issues of unfulfilled requirements in the recent npm (and node) updates

After updating npm and node to the latest versions, I am encountering the following errors and warnings: $ npm --version 2.4.1 $ node --version v0.10.36 $ npm install > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f895 ...

Is it possible to arrange two items in one column and the rest as columns in MaterialUI Grid?

I need help arranging my arrows in a MaterialUI grid where one points up and the other points down. How can I achieve this layout? Attached below is an image of my current setup and the desired outcome. Here is my code: <Paper className={classes.paper ...

Updating the value of a Redux-Form Checkbox Field using programming methods

I have created a registration form where users can accept or decline the terms of services. When a user accepts the terms, they click a button to check the checkbox. If they decline, the button will uncheck the checkbox. https://i.sstatic.net/mfkcY.png ht ...

Cleve js does not include delimiters in its date output

In my Vue.js project, I decided to implement a date input field using cleave.js. After passing the following options: options="{date: true, delimiter: '/', datePattern: ['m', 'd', 'Y']}" I encountered an issue wh ...

I'm having trouble getting my application to output to the console. What could be the issue?

In my cr-route.js file, I have a function that ensures the user is authenticated before displaying their name. module.exports = function (app, passport) { // ===================================== // HOME PAGE (with login links) ======== // == ...

What can I do to prevent masonry images from piling on top of one another?

I have been working on creating a photo gallery using the Bootstrap 5 example on masonry, and everything is working well so far. I have also successfully implemented modal boxes. However, the only issue I'm facing is with the JS Image Loaded not preve ...

What is the proper way to utilize JQuery and Ajax to communicate with a global function in writing?

My goal is to retrieve data from an AJAX request and store it in a global variable. Despite trying to make the call synchronous, I am encountering issues where the value of the global variable becomes undefined outside of the Ajax request. I have attempt ...

Dealing with an empty request.FILES using FileUploadParser in Django Rest Framework and Angular file upload technique

Uploading files in an angular view can sometimes be tricky, especially when using templates. The code snippet below shows how to upload multiple and single files using Angular File Upload library. Multiple <input type="file" name="file" nv-file-select= ...

How can JavaScript be used to parse an XML file? Should we consider using SAX for handling large XML files

Hello everyone, I am feeling very frustrated and overwhelmed with my current situation. I have been searching everywhere for a solution but seem to be going in circles. This will be my first attempt at working with xml and it's quite daunting, espec ...

How to dynamically display a div in Vue.js depending on the attributes of another element

I have a dilemma with my text container. My goal is to collapse the div if the text length exceeds a certain limit, and then display a button that says "...show more". When this button is clicked, the div should expand. Clicking it again should collapse th ...

What is the method to define a loosely typed object literal in a TypeScript declaration?

We are currently in the process of creating TypeScript definitions for a library called args-js, which is designed to parse query strings and provide the results in an object literal format. For example: ?name=miriam&age=26 This input will produce th ...

PANDAS: Transforming arrays into individual numbers in a list

My list is printing out as [array([7], dtype=int64), array([11], dtype=int64), array([15, 19, 23, 27, 31, 35, 39, 43, 47, 51, 55, 59, 63, 67], dtype=int64)] However, I want it to look like [7, 11, 15, 19, 23, ...] The issue arises when using pandas ...

Having trouble converting Buffered Byte Array into Image in Browser

Hello there! I am currently facing an issue while attempting to generate an image from a buffered byte array. The reason behind this is that I need to transfer the image from the server to the client using JSON. Below is the code snippet in question: The ...

Can TypeScript be used to dynamically render elements with props?

After extensive research on SO and the wider web, I'm struggling to find a solution. I have devised two components, Link and Button. In short, these act as wrappers for <a> and <button> elements with additional features like chevrons on t ...

Is there a method in AngularJS to have $http.post send request parameters rather than JSON?

I have come across some older code that utilizes an AJAX POST request using jQuery's post method. The code looks something like this: $.post("/foo/bar", requestData, function(responseData) { //do stuff with response } The request ...

Mobile devices do not support HTML5 Video playback

Here is the HTML5 Video code I am using: <div id="lightBox1" class="lightBox"> <video id="video" controls preload="metadata"> <source width="100%" height="470" src="/ImageworkzAsia/video/iworkzvid.mp4" type="video/mp4"> ...

React Intersection Observer Triggering Memory Leaks

Issue Description: I encountered a problem with my React app crashing on mobile. The Chrome dev tools revealed that garbage collection wasn't triggering, and upon inspecting the heap, I found that the top constructors by retained size were all linked ...

The charAt function in a basic JavaScript if statement is failing to execute

When a user inputs a number that does not start with 6 or 9, an error occurs: console.log($(this).val().charAt(0)); if($(this).val().charAt(0) != 6 || $(this).val().charAt(0) != 9){ x=false; }else { x=true; } The console.log function corre ...

Is it possible to refresh text in table without clearing icons?

Is there a way to maintain icons in table rows when editing text fields from a dialog? Currently, regardless of whether I use .html() or .text(), the icons disappear. I suspect that utilizing .content() may be a solution, but I'm unsure how to impleme ...