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.
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' } ]
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' } ]