How to selectively filter an array of objects using another array in JavaScript

Imagine you have an array filled with objects:

people = [
    {id: "1", name: "abc", gender: "m", age:"15" },
    {id: "2", name: "a", gender: "m", age:"25" },
    {id: "3", name: "efg", gender: "f", age:"5" },
    {id: "4", name: "hjk", gender: "m", age:"35" },
    {id: "5", name: "ikly", gender: "m", age:"41" },
    {id: "6", name: "ert", gender: "f", age:" 30" },
    {id: "7", name: "qwe", gender: "f", age:" 31" },
    {id: "8", name: "bdd", gender: "m", age:" 78" },
]

Additionally, you also have an array containing desired ids:

id_filter = [1,4,5,8]

Your task is to filter the people array to only show the specified ids from id_filter where the gender is set to m.

Answer №1

An easy method for sorting data is by utilizing the array's filter() function, like shown below:

users.filter(user => id_filter.includes(user.id))

Answer №2

If you want to achieve the desired output, you can utilize array.filter() method with specific conditions. I have also made corrections to your JSON structure.

var filtered = people.filter(function(item) {
        return id_filter.indexOf(item.id) !== -1 && item.gender==='m';
});

DEMO

var  people =[
  { "id": 1, "name": "abc", "gender": "m","age": "15" },
  { "id": 2, "name": "a", "gender": "m", "age": "25"  },
  { "id": 3,"name": "efg", "gender": "f","age": "5" },
  { "id": 4,"name": "hjk","gender": "m","age": "35" },
  {  "id": 5, "name": "ikly","gender": "m","age": "41" },
  { "id": 6, "name": "ert", "gender": "f", "age": "30" },
  { "id": 7, "name": "qwe", "gender": "f", "age": "31" },
  { "id":8, "name": "bdd",  "gender": "m", "age": " 8" }
];
var id_filter = [1,4,5,8];
var filtered = people.filter(function(item) {
    return id_filter.indexOf(item.id) !== -1 && item.gender==='m';
});
console.log(filtered);

Answer №3

Using the Array.includes() method:

var people = [
    {id : "1", name : "abc", gender : "m", age :"15" }, {id : "2", name : "a", gender : "m", age :"25" },
    {id : "3", name : "efg", gender : "f", age :"5" },  {id : "4", name : "hjk", gender : "m", age :"35" },
    {id : "5", name : "ikly", gender : "m", age :"41" }, {id : "6", name : "ert", gender : "f", age :" 30" },
    {id : "7", name : "qwe", gender : "f", age :" 31" }, {id : "8", name : "bdd", gender : "m", age :" 78" }
], 
    id_filter = [1,4,5,8],
    result = people.filter((o) => id_filter.includes(+o.id) && o.gender == "m");       

console.log(result);


  • +o.id - The + symbol is used to convert a numeric string into a number

Answer №4

If you want to accomplish this, you can utilize the code snippet below:

const filtered_people = people.filter(function(person){
    return id_filter.includes(person.id) && person.gender === 'm';
});

Ensure that each person's id is an integer and not a string, as shown in your example. Otherwise, the includes() function will fail to match. Additionally, there seem to be syntax errors within your people array. Therefore, the corrected code should appear like this:

const people = [
    {id: 1, name: "abc", gender: "m", age:15},
    {id: 2, name: "a", gender: "m", age: 25},
    {id: 3, name: "efg", gender: "f", age: 5},
    {id: 4, name: "hjk", gender: "f", age: 35},
    {id: 5, name: "ikly", gender: "m", age: 41},
    {id: 6, name: "ert", gender: "f", age: 30},
    {id: 7, name: "qwe", gender: "f", age: 31},
    {id: 8, name: "bdd", gender: "m", age: 78}
]
const id_filter = [1,4,5,8]
const filtered_people = people.filter((person) => id_filter.includes(person.id) && person.gender === 'm')
console.log(filtered_people)

I trust this guidance proves beneficial. Best of luck.

Answer №5

If you encounter this scenario, utilizing the filter and include methods can be beneficial. Remember that since your ids are in string format, they will need to be converted before being used.

var filteredResult = individuals.filter((individual) => (idList.includes(parseInt(individual.id)) && individual.gender === 'male'))

Answer №6

When approaching this scenario, it is more efficient to travel by foot. Start by looping through the people array, then compare each person's ID with the filter list.

for(person in people) {
     for(id in id_filter) {
         if(person[id] == id && person[gender] == "m"){

         }
     }
}

Answer №7

To apply the Array.prototype.filter method, you can utilize the following code snippet:

function filterByGender(arr, indexes, gender) {                              // this function takes an array of people arr, an array of indexes ids, and a gender to filter and return the matching people objects from arr
  return arr.filter(function(person) {                              // filters each person object...
    return indexes.includes(person.id) && person.gender === gender;        // checks if this person's id is in the provided indexes array and if their gender matches the specified one
  });
}

var individuals = [{id:"1",name:"John",gender:"m",age:25},{id:"2",name:"Jane",gender:"f",age:30},{id:"3",name:"Alex",gender:"m",age:45},{id:"4",name:"Emily",gender:"f",age:28},{id:"5",name:"Sam",gender:"m",age:33}];

console.log(filterByGender(individuals, ["1", "3", "5"], "m"));               // filters elements with ids ["1", "3", "5"] and gender "m".

Note: The id property values in the individuals array are strings so when using includes, make sure to either provide string ids or convert the id property to numbers before comparison.

Answer №8

To optimize performance for a large id_filter, the best approach is to convert it into a new Set(). This conversion allows for constant-time lookup. Subsequently, you can utilize the .filter() method to iterate through your people array and return true if the set contains the id and the gender is 'm'.

const people = [ {id: "1", name: "abc", gender: "m", age:"15" }, {id: "2", name: "a", gender: "m", age:"25" }, {id: "3", name: "efg", gender: "f", age:"5" }, {id: "4", name: "hjk", gender: "m", age:"35" }, {id: "5", name: "ikly", gender: "m", age:"41" }, {id: "6", name: "ert", gender: "f", age:" 30" }, {id: "7", name: "qwe", gender: "f", age:" 31" }, {id: "8", name: "bdd", gender: "m", age:" 78" }, ];

const id_filter = new Set([1,4,5,8]);
const res = people.filter(({id, gender}) => id_filter.has(+id) && gender === 'm');
console.log(res);

This optimized approach results in a time complexity of O(N + k), which is far better than the O(Nk) complexity incurred by using methods like .includes() or .indexOf(). Here, N represents the length of the people array, while k represents the length of the id_filter array.

Answer №9

const people = [
    {id: "1", name: "abc", gender: "m", age: "15" },
    {id: "2", name: "a", gender: "m", age: "25" },
    {id: "3", name: "efg", gender: "f", age: "5" },
    {id: "4", name: "hjk", gender: "m", age: "35" },
    {id: "5", name: "ikly", gender: "m", age: "41" },
    {id: "6", name: "ert", gender: "f", age: " 30" },
    {id: "7", name: "qwe", gender: "f", age: " 31" },
    {id: "8", name: "bdd", gender: "m", age: " 78" },
]

const idFilter = [1,4,5,8]

const idIsInList = id => idFilter.includes(+id) // Ensuring it is a number, not a string
const genderIsMale = gender => gender === "m"
const result = people.filter(item => idIsInList(item.id) && genderIsMale(item.gender))

console.log(result)

Answer №10

    individuals = [
        {id : "1", name : "abc", gender : "m", age :"15" },
        {id : "2", name : "a", gender : "m", age :"25" },
        {id : "3", name : "efg", gender : "f", age :"5" },
        {id : "4", name : "hjk", gender : "m", age :"35" },
        {id : "5", name : "ikly", gender : "m", age :"41" },
        {id : "6", name : "ert", gender : "f", age :" 30" },
        {id : "7", name : "qwe", gender : "f", age :" 31" },
        {id : "8", name : "bdd", gender : "m", age :" 78" }
    ]
    var id_filter = ["1","4","5","8"], selectedIndividuals = []; 
    for( var i=individuals.length-1; i>=0; --i){ 
      if( id_filter.indexOf( individuals[i].id ) != -1 ){ 
        selectedIndividuals.push( individuals[i] ); 
      } 
    }
    console.log( selectedIndividuals );

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

Create a unique type in Typescript that represents a file name with its corresponding extension

Is there a way for me to specify the type of a filename field in my object? The file name will consist of a string representing the name of the uploaded file along with its extension. For instance: { icon: "my_icon.svg" } I am looking for a ...

JavaScript Button with the Ability to Input Text in a TextArea?

For instance, imagine a scenario where you click on a button and it then displays various options for you to select from. Whatever option you pick will be automatically inserted into the text area. ...

Tips for enabling auto-scroll feature in MuiList

Currently, I am working on a chat window component that utilizes Material UI for styling. I expected that setting a height or max-height on either the MuiList or MuiBox encapsulating the list would automatically scroll to the new message when it's sen ...

Requesting data asynchronously using AJAX and displaying the filtered results on a webpage using JSON

When I send a request to my node.js server for a .json file containing person information (first name, last name), I want the data to be filtered based on user input. For example: When I request the .json file from the server, it gives me a list of people ...

Issue with SVG on tainted canvas causes IE security error when using toDataURL

In my Angular JS directive, I have implemented a feature to export SVGs to PNG. While this functionality works seamlessly in most browsers, it encounters a security error in IE. Despite my numerous attempts to troubleshoot the issue, I have been unable to ...

Adjust the canvas size to fit its parent element ion-grid

I am currently working on an Ionic 3 component that displays a grid of images connected by a canvas overlay. I have utilized Ionic's ion-grid, but I am facing an issue with resizing the canvas. The problem is that I cannot determine the correct dimens ...

OpenLayers' circular frames surrounding the icons

I am currently using openlayers and trying to implement a feature that creates a circle around the icons on the map. I have been referring to this example on Stack Overflow but unable to draw the circle successfully. Can someone please assist me with this? ...

Angular 2: Navigating through submenu items

I have a question about how to route submenu elements in Angular 2. The structure of my project is as follows: -app ---login ---registration ---mainApp (this is the main part of the app, with a static menu and links) -----subMenu1 (link to some con ...

Looping through multiple AJAX calls

I have come across numerous questions on this topic, but I am still struggling to find a solution that will make my code function correctly. There is a specific function for calling AJAX that I am unable to modify due to security restrictions. Here is how ...

What is the step-by-step process for chaining ajax requests using $q.deffer?

I have a task that requires the browser to make N requests to the server, where the requests must be synchronous and start only after the previous request has completed. One way to achieve this is by writing a function with a for loop and recursively call ...

Problem with sidebar animation: Functioning properly when open, but closes abruptly without animation in React using Tailwind CSS

When interacting with my Menu react component by clicking on the 'hamburger' icon that I created manually, the sidebar menu opens smoothly with an animation. However, the issue arises when trying to close the sidebar as it vanishes instantly with ...

Nest an array inside another array using a foreach loop

I've successfully created a code that generates two arrays using foreach loop and existing data. Now, I am looking to merge these two arrays into one. Below is the code for the first array : $sql = "SELECT photoprofile,username from photo WHERE usern ...

Updating columns in MongoDB using arrays in JavaScript has just gotten easier

When trying to update a mongoDB collection with an array value, the update fails without any error message. This method causes the issue: var arr = ["test","test1","test2"]; $.ajax('http://my.mongodb.com/collection?id=80a2c727de877ac9' , { ...

Error in Typescript: Function expects two different types as parameters, but one of the types does not have the specified property

There's a function in my code that accepts two types as parameters. handleDragging(e: CustomEvent<SelectionHandleDragEventType | GridHandleDragEventType>) { e.stopPropagation(); const newValue = this.computeValuesFromPosition(e.detail.x ...

When using Vue.js, binding may not function properly if it is updated using jQuery

Link to JsFiddle Below is the HTML code: <div id="testVue"> <input id="test" v-model="testModel"/> <button @click="clickMe()">Click me</button> <button @click="showValue()">Show value</button> </div& ...

Using <Redirect/> in ReactJS results in rendering of a blank page

Hello everyone, I've been working on a feature where I want to redirect the user to the home page using <Redirect/> from react-router after they have successfully logged in. However, I'm facing an issue where the timeout is functioning corr ...

JavaScript - Utilizing an image file in relation to a URL pathway

Is there a way to reference an image URL using a relative path in a JavaScript file similar to CSS files? To test this, I created two divs and displayed a gif in the background using CSS in one and using JavaScript in the other: -My file directory struct ...

Issues with the functionality of Google Translate's JavaScript code snippet are causing

After trying out the code snippet provided on w3schools.com, I encountered a discrepancy between the results displayed on the website and those on my personal computer. <div id="google_translate_element"></div> <script> function googleT ...

Handling TextChanged Event of a TextBox in ASP.NET using C#

I'm currently designing a POS screen that allows barcode scanning directly into a textbox. I want to implement a code behind procedure that adds the barcode-related data to the grid as soon as the textbox text changes. This is how my textbox looks: &l ...

What are the strategies for distinguishing between languages in React Native prior to mounting the component?

I had high hopes for this solution, but unfortunately it doesn't work as expected. The issue is that this.text.pupil is undefined. Could the problem possibly be related to componentWillMount? If so, how can I handle multiple languages outside of ...