Guide to sorting a JavaScript array using a filter object

Using a dynamically generated filter object from a multi-search UI component, the data needs to be filtered based on the criteria. Once the user initiates a search, the data will be filtered accordingly. Below is an example of the filter object and sample data along with the expected output.

var filter = {
  city: 'pana',
  hospname: 'sara'
};
var data = [
  {
    "city": "Hot Springs",
    "hospname": "St. Vincent Hot Springs",
    "version": "VA48A",
    "sysid1": "CT67400",
    "type": "CompressedFile",
    "rowIndex": 0,
    "selected": false,
    "disabled": true
  },
  {
    "city": "Panama City",
    "hospname": "Bay Medical Center",
    "version": "VA48A",
    "sysid1": "CT67399",
    "type": "CompressedFile",
    "rowIndex": 1,
    "selected": false,
    "disabled": true
  },
  {
    "city": "Sarasota",
    "hospname": "Sarasota Memorial Hospital",
    "version": "VA44A",
    "sysid1": "C7393",
    "type": "CompressedFile",
    "rowIndex": 2,
    "selected": false,
    "disabled": true
  },
  {
    "city": "DAVENPORT",
    "hospname": "Genesis Medical Center",
    "version": "VA48A",
    "sysid1": "C6333",
    "type": "CompressedFile",
    "rowIndex": 6,
    "selected": false,
    "disabled": true
  }
];

Desired Output:

[{
    "city": "Panama City",
    "hospname": "Bay Medical Center",
    "version": "VA48A",
    "sysid1": "CT67399",
    "type": "CompressedFile",
    "rowIndex": 1,
    "selected": false,
    "disabled": true
  },
  {
    "city": "Sarasota",
    "hospname": "Sarasota Memorial Hospital",
    "version": "VA44A",
    "sysid1": "CT67393",
    "type": "CompressedFile",
    "rowIndex": 2,
    "selected": false,
    "disabled": true
  }]

Answer №1

My journey began with a more versatile approach, allowing the addition of attributes on the filter object.

var filter = {
  city: 'pana',
  hospname: 'sara'
};
var data = [
  {
    "city": "Hot Springs",
    "hospname": "St. Vincent Hot Springs",
    "version": "VA48A",
    "sysid1": "CT67400",
    "type": "CompressedFile",
    "rowIndex": 0,
    "selected": false,
    "disabled": true
  },
  {
    "city": "Panama City",
    "hospname": "Bay Medical Center",
    "version": "VA48A",
    "sysid1": "CT67399",
    "type": "CompressedFile",
    "rowIndex": 1,
    "selected": false,
    "disabled": true
  },
  {
    "city": "Sarasota",
    "hospname": "Sarasota Memorial Hospital",
    "version": "VA44A",
    "sysid1": "C7393",
    "type": "CompressedFile",
    "rowIndex": 2,
    "selected": false,
    "disabled": true
  },
  {
    "city": "DAVENPORT",
    "hospname": "Genesis Medical Center",
    "version": "VA48A",
    "sysid1": "C6333",
    "type": "CompressedFile",
    "rowIndex": 6,
    "selected": false,
    "disabled": true
  }
];

let results;

if (Object.keys(filter).length === 0)
  results = data;
else {
  results = data.filter((item) => {
      return Object.keys(filter).find(key => {
          return item[key] && item[key].toLowerCase().includes(filter[key].toLowerCase());
      });
  });  
}

console.log(results);

Answer №2

var filter = {
  city: 'pana',
  hospname: 'sara'
};
var data = [
  {
    "city": "Hot Springs",
    "hospname": "St. Vincent Hot Springs",
    "version": "VA48A",
    "sysid1": "CT67400",
    "type": "CompressedFile",
    "rowIndex": 0,
    "selected": false,
    "disabled": true
  },
  {
    "city": "Panama City",
    "hospname": "Bay Medical Center",
    "version": "VA48A",
    "sysid1": "CT67399",
    "type": "CompressedFile",
    "rowIndex": 1,
    "selected": false,
    "disabled": true
  },
  {
    "city": "Sarasota",
    "hospname": "Sarasota Memorial Hospital",
    "version": "VA44A",
    "sysid1": "C7393",
    "type": "CompressedFile",
    "rowIndex": 2,
    "selected": false,
    "disabled": true
  },
  {
    "city": "DAVENPORT",
    "hospname": "Genesis Medical Center",
    "version": "VA48A",
    "sysid1": "C6333",
    "type": "CompressedFile",
    "rowIndex": 6,
    "selected": false,
    "disabled": true
  }
];

const result=data.filter(item=>item.city.toLowerCase().includes(filter.city.toLowerCase()) || item.hospname.toLowerCase().includes(filter.hospname.toLowerCase()) )

console.log(result)
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №3

If you're using ES6, you have the ability to achieve this in the following way:

let results = data.filter((item) => {
   return item.city === filter.city || item.hospname === filter.hospname;
});

Keep coding joyfully!

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

Discover the correct steps to transition from using particles.js to the react-tsparticles package

Migrating from react-particles-js to react-tsparticles-js Hi there! I'm currently facing an issue with my ReactJS website here, which is deployed using Netlify. The error code below keeps popping up, and I believe it's related to the transition ...

A guide on accessing array values in MongoDB using Python syntax

Kindly, handle with care I have a mongo doc structured like this : { "Institute" : "Ucambridge", "Project" : [ #array of projects {"Sample":[ #array of samples { "workflow" : "abc", "owner" : "peter" } ...

The system encountered an issue while trying to access the 'bannable' property, as it was undefined

message.mentions.members.forEach(men => { let member = message.mentions.members.get(men) if (!member.bannable) return message.reply(not_bannable) const reason = args.slice(1).join(" "); member.ban({reason: reason ...

"Allow users to select only the year with Material-UI DatePicker

Is there a method to display solely years using the Material UI DatePicker component in React? I would like to enable users to choose only the year, excluding months or days. Please note that neither the openToYearSelection option nor the autoOk feature ...

Is there a way to include a lockfile in a docker container as an optional step?

I am attempting to create a docker image that can optionally incorporate a yarn or npm lockfile during the build process. I want to include it explicitly, but also ensure that the build does not fail if the lockfile is missing. The goal is to respect dete ...

Creating individual product pages from an array of objects: A step-by-step guide

Is there a way in Next.js to create individual pages for each object in an array with unique URLs? Here is the input array: Input Array const products = [ { url: "item-1", id: 1, name: "Item 1", description: "lor ...

Utilizing React JS with Material-UI Autocomplete allows for seamlessly transferring the selected item from the renderInput to the InputProps of the textfield component

Exploring the functionality of the updated version of Autocomplete, my goal is to ensure that when an element is chosen from the dropdown menu, the input format of the text field will be modified to accommodate adding a chip with the selected text. Is the ...

Locate an object for editing or adding changes

My scenario involves the existence of an object named productCounts [{provisioned=2.0, product=str1, totalID=1.0}, {product=str2, provisioned=4.0, totalID=3.0}, {provisioned=6.0, product=str3, totalID=5.0}] In addition, there is an array labeled uniqu ...

attempting to retrieve numerical variable beyond the function in jQuery

Trying to implement a star rating system and need to access the rating number for further actions. How can I make the number variable accessible outside of the click function? $(document).ready(function () { $(".li").mouseover(functio ...

The orientation of the mesh in relation to its parent entity

Currently tackling a project involving the creation of a 3D Widget for rotating, scaling, and translating a mesh. Facing challenges with positioning the cone used for scaling the parent mesh. Here is the code snippet in question: function generateScaleWid ...

Tips for incorporating external functions into Vue Component data synchronization:

As someone new to JavaScript, I am trying to incorporate external functions into Vue component data bindings, but I am encountering issues. helper.js function groupArrayOfObjects(list, key) { return blah blah } function parseDate(d) { ret ...

Encountering trouble with displaying data in Express and Mongoose

Struggling to comprehend how to define and utilize an API in Express, while using Mongoose to connect with MongoDB. Successfully saving objects from input on the front end, but getting lost when it comes to retrieving and displaying the saved data. Take a ...

Unable to upload images on Phonegap ios using formdata

I am facing an issue with image upload in my Phonegap application for iOS. The image upload is not working at times and I am unsure of the exact reason behind this. I am using FormData to upload the image as shown below: <input id="uploadImage" type="f ...

Guide to generating a new element and displaying updated data whenever it is retrieved in a React application

I'm completely new to React and I'm struggling with rendering and listing data fetched from Firebase on my HTML page. I attempted the following approach: const Music = ({ match }) => { const [titles, setTitles] = useState([]); // Change ...

How can I enter a single backslash for location input in node.js without using double backslashes?

I have a project where the user needs to input a word to search for in files along with the folder location. However, I am struggling to write code that allows the user to input the location using single backslashes instead of double backslashes. const fol ...

The function of the Angular ng-include form action for posting a URL appears to be malfunctioning

When a form post is included in a parent HTML using ng-include, it does not trigger the submission action. <div ng-include src="'form.html'"></div> The code in the form.html file is as follows: <form action="next/login" method = ...

Comparing parameters between two functions in Javascript: a step-by-step guide

I am currently working on solving this problem: var name; var totalScore; var gamesPlayed; var player; var score; // Creating the game player object function makeGamePlayer(name, totalScore, ga ...

gulp-uglify is responsible for the malfunction of the constructor.name property

When I make a change in my gulpfile.js by commenting out the line .pipe(uglify({ preserveComments: 'some'})) my code appears neat and tidy, and the next line functions correctly: if(Mystudy.constructor.name != "MyStudyView") However, ...

Creating a dynamic interaction between HTML forms and JavaScript using the onsubmit event handler

Having trouble getting my JavaScript file to fire when clicking the submit button on my simple HTML form. Can anyone provide some assistance? **UPDATED CODES Here is a snippet of my condensed HTML file: <html> <form name="form01" id="form01" ac ...

Issue with Vue JS Components: Button function not working on second click with @click

I've been working with Vue JS and Laravel to create a modal. The first time I press the button with @click, it works fine but the next time I encounter an error. Here's my Laravel Blade code: <div class="col-span-12 mb-5" id="a ...