Reputation: 335
How to filter index value in foreach Javascript with condition if
last_login = null
then store the filtered values to
this.searchLogin
Image below is the ouput of: console.log(obj);
Here' what I've done so far:
try {
this.searchTrigger = true
var obj = this.list;
this.searchLogin = [];
for (let i=0; i < obj.length; ++i){
if(obj.filter( x => obj[i].profile.last_login === null)){
this.searchLogin.push(obj[i]);
}
}
console.log('This are obj data passed to search login',this.searchLogin);
Upvotes: 1
Views: 820
Reputation: 1194
var obj = [
{ profile: { last_login: null } },
{ profile: { last_login: true } },
{ profile: { last_login: null } },
{ profile: { last_login: true } },
{ profile: { last_login: null } }]
//With filter and map
console.log("With filter and map: ",
obj.map((x, i) => ({ ...x.profile, i }))
.filter(x => !x.last_login)
.map(x => x.i));
//With reduce
console.log("With reduce: ",
obj.reduce((p, c, i) => (!c.profile.last_login && p.push(i), p), [])
)
Upvotes: 1
Reputation: 28475
There are some points that need to be noted
filter
function will return an array and even if it empty (no matched results), it will still be evaluated as true i.e. your if condition will always be executedif
condition has a filter function inside a for loop which means that you are unnecessarily checking condition for same object for all the objects in array i.e. for each object the filter function will either return empty array or array of all the objects. You can use Array.reduce and store the last_login
information in the resultant array
this.searchLogin = this.list.reduce((a,c) => c.profile.last_login === null ? a.concat(c.profile.last_login) : a, []);
Upvotes: 0
Reputation: 2630
I think no need to save the results explicitly to an array again, the filter on array by itself will create an results array based on the filter condition.
For more on filter,
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
In your case,
this.searchLogin = obj.filter( x => x.profile.last_login === null);
would do the trick.
Upvotes: 0