larry chambers
larry chambers

Reputation: 513

Check something exists in array before executing

I have a array below that is constantly changing. It is being using in a node.js app. I have everything working good that updates elements of the array but if I restart node and the browser is still running, the webpage still sends data and causes it to crash, so I need to check if array exists before it tries to do something.

My array is like this, called users :-

[ { username: 'a',
    active: true,
    lat: '52.4099584',
    lng: '-1.5310848' } ]

So I need to check username 'a' exists. I have tried

users.map(obj => obj.username).indexOf(value) >= 0;

but doesnt work?

Any suggestions?

Thanks

Upvotes: 1

Views: 56

Answers (1)

kockburn
kockburn

Reputation: 17616

If you're looking to remve the users that don't have a username, then you could do something like this.

const data = [{ 
    username: 'a',
    active: true,
    lat: '52.4099584',
    lng: '-1.5310848' },
   { 
    username: undefined,
    active: true,
    lat: '52.4099584',
    lng: '-1.5310848' }];
    
    
console.log(data.filter(({username})=> username && username !== null));

Otherwise, you should just use something like every

const data = [ { 
    username: undefined,
    active: true,
    lat: '52.4099584',
    lng: '-1.5310848' },
    { 
    username: 'a',
    active: true,
    lat: '52.4099584',
    lng: '-1.5310848' }];


console.log(data.every(({username})=> username && username !== null));

Or findIndex

const data = [ { 
        username: undefined,
        active: true,
        lat: '52.4099584',
        lng: '-1.5310848' },
        { 
        username: 'a',
        active: true,
        lat: '52.4099584',
        lng: '-1.5310848' }];


    console.log(data.findIndex(({username})=> !username || username === null) > -1);

Upvotes: 1

Related Questions