Use the filter method to sort through an array of objects by using another array

I need to filter an array using two criteria: one is straightforward (==1) and the other involves an array. In this example, I want to filter where level = 0 or name includes ['B','S'].

[
{id: 1, level: 0, name: 'A'},
{id: 2, level: 1, name: 'B'},
{id: 3, level: 1, name: 'S'},
{id: 4, level: 0, name: 'A'},
{id: 5, level: 0, name: 'S'},
{id: 6, level: 1, name: 'A'},
{id: 7, level: 0, name: 'B'}, ]

Therefore, the desired result would be:

[
{id: 1, level: 0, name: 'A'},
{id: 2, level: 1, name: 'B'},
{id: 3, level: 1, name: 'S'},
{id: 4, level: 0, name: 'A'},
{id: 5, level: 0, name: 'S'},
{id: 7, level: 0, name: 'B'}, ]

Due to limitations with ecmaScript-5, I am unable to use .includes which could have been helpful in this case.

Furthermore, I prefer to utilize the .filter function. Any suggestions on how to achieve this?

Thank you.

Answer №1

If you're working with ecmaScript-5, here's a neat trick:

var data = [{ id: 1, level: 0, name: 'A' },{ id: 2, level: 1, name: 'B' },{ id: 3, level: 1, name: 'S' },{ id: 4, level: 0, name: 'A' },{ id: 5, level: 0, name: 'S' },{ id: 6, level: 1, name: 'A' },{ id: 7, level: 0, name: 'B' },]

var filteredData = data.filter(function (item) {
  return item.level === 1 || ['B', 'S'].indexOf(item.name) > -1;
})


console.log(filteredData)

Answer №2

A straightforward method to achieve this would be to use a simple loop to push the matching items into a new array that contains only the desired items.

Instead of opting for fancier methods, I chose to stick with the traditional approach using 'var' and 'forEach' to meet your requirement for ECMAScript 5 compatibility.

var arr = [
{id: 1, level: 0, name: 'A'},
{id: 2, level: 1, name: 'B'},
{id: 3, level: 1, name: 'S'},
{id: 4, level: 0, name: 'A'},
{id: 5, level: 0, name: 'S'},
{id: 6, level: 1, name: 'A'},
{id: 7, level: 0, name: 'B'}, ]

var newArr = [];

arr.forEach(function(item) {
  if(item.level === 1 || (item.name === 'A' || item.name ==='B')) {
   newArr.push(item)
  }
})


console.log(newArr);

//output:[
  //{id: 1,level: 0, name": "A"},
  //{id: 2, level: 1, name: "B"},
  //{id: 3, level: 1, name: "S"},
  //{id: 4, level: 0, name: "A"},
  //{id: 6, level: 1, name: "A"},
  //{id: 7, level: 0, name: "B"}]

Answer №3

let data = [
  { id: 1, level: 0, name: 'A' },
  { id: 2, level: 1, name: 'B' },
  { id: 3, level: 1, name: 'S' },
  { id: 4, level: 0, name: 'A' },
  { id: 5, level: 0, name: 'S' },
  { id: 6, level: 1, name: 'A' },
  { id: 7, level: 0, name: 'B' },
];

let newData = data.filter(
  element => element.level === 0 || element.name === 'B' || element.name === 'S'
);

console.log(newData);

Answer №4

To efficiently filter an array based on specific criteria, you can leverage the powerful combination of the Array.prototype.filter() method and the Array.prototype.indexOf() method:

const data = [
  {id: 1, level: 0, name: 'X'},
  {id: 2, level: 1, name: 'Y'},
  {id: 3, level: 1, name: 'Z'},
  {id: 4, level: 0, name: 'X'},
  {id: 5, level: 0, name: 'Z'},
  {id: 6, level: 1, name: 'X'},
  {id: 7, level: 0, name: 'Y'},
];

var criteria = ['Y', 'Z'];

var filteredResult = data.filter(item => item.level === 0 || criteria.indexOf(item.name) !== -1);

console.log(filteredResult)

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

Client-side filtering of jqGrid with multiple conditions

I am faced with a challenge in filtering records in a jqGrid based on multiple conditions. For example, if there are columns for Name, Age, and City, and I need to filter the grid using the following condition: Name = "Mark" and Age = 25 and City = &apos ...

issue with mongoose virtual populate (unable to retrieve populated field)

During my project using mongoose with typescript, I encountered an issue with adding a virtual called subdomains to populate data from another collection. Although it worked without any errors, I found that I couldn't directly print the populated data ...

What are the steps to effectively utilize data retrieved from readFragment using Apollo?

Once a user logs in, the system returns a jwt token and a user object containing the id and firstName, which are then stored in cache (refer to the image link provided below). https://i.stack.imgur.com/oSXZ5.png I aim to retrieve the user information fro ...

Delaying loops with JQuery Ajax

I am attempting to implement a delay in my AJAX data processing so that the loop runs a bit slower. Here's the code I'm working with: $(document).ready(function (){ $('#button').click(function(){ $('#hide').show ...

"JQuery was unable to retrieve the JSON data as it

I am currently working on creating a reservation system using PHPJabbers' free script. One issue I am facing is with outputting the price when a user selects a date. Below is the JavaScript code that I am using: /** * @@@ * DateTimePicker / Availab ...

Show notifications after being redirected to a new page

My goal is to submit a form and have the page redirected to a different URL upon submission. Currently, everything works as expected, but there is an issue with the timing of the toast message. The toast message appears immediately after the user clicks th ...

Efficient search operations in a 2D matrix in C++

Currently, my code utilizes a 2D array and the process of searching for a specific entry is proving to be time-consuming. I am seeking recommendations on optimizations that can be implemented to reduce the search time within this 2D array. Any suggestion ...

What is the process for making a POST request with the Google Chrome Puppeteer library?

Hello everyone, I'm currently attempting to make a POST request using the puppeteer headless chrome library. I'm running into some issues with the code below and can't seem to figure out what's wrong. // Obtain the csrf token ...

Breaking circular dependencies in JavaScript is a common challenge that developers face when

Having encountered a circular dependency issue between certain JS files, I am seeking steps to resolve it. Q1: Is repositioning the require function an appropriate solution? One suggested approach to resolve this issue is to move the require() statement ...

Immediate family members nearby are not an option. We will have to create the form dynamically

On a previous page, there is a form that allows users to input data and define the number of "Attributes" they want to assign to a device by clicking on a button. Users are prompted to specify a name and type for each attribute. If the user selects "Selec ...

Accessing/Storing Pictures in MongoDB using Mongoose

I've been struggling with managing images in MongoDB for a while now. Everywhere I look suggests using GridFS because of the 16mb size limit per document. However, the documents I want to store are all <16mb each. Currently, I am storing it like th ...

Using Javascript to open a PDF in a new tab directly from a byte array

I am currently using AngularJS along with an HTTP resource to make a request to an external API. The response I am getting back is in the form of a byte array. My goal is to convert this byte array into a PDF and open it in a new window. So far, I have not ...

Using jQuery to include the value of an array index in the output

Looking for guidance on jQuery & JavaScript. I have successfully implemented code that adds a new text input field based on the user's selection from a dropdown select field. <script> $(function() { var input = $('<input placeholder= ...

What is the method for combining two box geometries together?

I am looking to connect two Box Geometries together (shown in the image below) so that they can be dragged and rotated as one object. The code provided is for a drag-rotatable boxgeometry (var geometry1). What additional code do I need to include to join t ...

The switch switches on yet another switch

Greetings everyone, Currently, I am in the midst of my exam project and creating a mobile menu. The functionality is there, but unfortunately, when closing the menu, it also triggers the search toggle which displays an unwanted div, becoming quite botherso ...

How can I implement a redirect function for Carousel image clicks in a React project?

I am working on a React project that includes Carousel from the 'react-responsive-carousel' npm package. I am looking to implement a functionality where clicking on the images in the Carousel will redirect to another component. How can this be ac ...

Developing two-dimensional arrays within PL/SQL codebases

Could you assist me in creating a two-dimensional array in PL/SQL for a Stored Procedure? The columns are dynamic, so they may grow and change in types as well. Any help would be greatly appreciated. Thank you in advance! This is the code I currently have ...

Are there any resources available for optimizing performance on iOS and Android browsers?

Being a web developer means considering the Android and iOS web browsers, which have their own rendering engines and limitations in power and memory. This can pose many complications. Therefore, I'm curious if there is a detailed guide available for ...

Execute a function that handles errors

I have a specific element that I would like to display in the event of an error while executing a graphql query (using Apollo's onError): export const ErrorContainer: React.FunctionComponent = () => { console.log('running container') ...

A helpful tip on incorporating Snack Bar Material UI within an if statement

When my Camera Component encounters an error, I want to display a snackbar notification. I attempted to encapsulate the component within a function and pass the error message as props, calling it in the if statement. However, this approach did not work as ...