0

Below is the array with objects:

myArray:[    
    {"name":"Ram", "email":"ram@gmail.com", "userId":"HB000006"},    
    {"name":"Shyam", "email":"shyam23@gmail.com", "userId":"US000026"},  
    {"name":"John", "email":"john@gmail.com", "userId":"HB000011"},    
    {"name":"Bob", "email":"bob32@gmail.com", "userId":"US000106"}   
    ]}  

I tried this but I am not getting output:

    item= myArray.filter(element => element.includes("US"));

I am new to Angular.

halfer
  • 19,824
  • 17
  • 99
  • 186
Manjunath
  • 9
  • 2
  • 1
    Your code assumes that `myArray` is an array of strings, not an array of objects with properties as strings. – halfer Jan 02 '22 at 10:23

2 Answers2

0

As noted by @halfer - You need to filter on the property that you are interested in - in this case - 'userId' - you can do this by simply adding the property into the code you already had tried and it will log out the specified items - or alternatively - you can make a utility function that takes the array, property and target string as arguments and this will allo2w you to search / filter other arrays and by any property and target string .

These two options are shown below and both log out the same results.

const myArray = [    
    {"name":"Ram", "email":"ram@gmail.com", "userId":"HB000006"},    
    {"name":"Shyam", "email":"shyam23@gmail.com", "userId":"US000026"},  
    {"name":"John", "email":"john@gmail.com", "userId":"HB000011"},    
    {"name":"Bob", "email":"bob32@gmail.com", "userId":"US000106"}   
    ]
    
// option 1 - direct filtering
const matchingItems = myArray.filter(element => element.userId.includes("US"));
console.log(matchingItems);

// gives - [ { name: 'Shyam', email: 'shyam23@gmail.com', userId: 'US000026' }, { name: 'Bob', email: 'bob32@gmail.com', userId: 'US000106' } ]


//option 2 - create a function that takes arguments and returns the matches
const matches = (arr, prop, str) => {
 return  arr.filter(element => element[prop].includes(str));
}
console.log(matches(myArray, 'userId', 'US'));

// gives - [ { name: 'Shyam', email: 'shyam23@gmail.com', userId: 'US000026' }, { name: 'Bob', email: 'bob32@gmail.com', userId: 'US000106' } ]
gavgrif
  • 15,194
  • 2
  • 25
  • 27
0
let filteredArray = myArray.filter(function (item){
        return item.userId.substring(0,2).includes('US')
    })
    Console.log(filteredArray)

//Output

[ { name: 'Shyam', email: 'shyam23@gmail.com', userId: 'US000026' }, { name: 'Bob', email: 'bob32@gmail.com', userId: 'US000106' } ]