hezzag
hezzag

Reputation: 23

Comparing values within one JavaScript array of objects

I have an array of objects like so:

[{ value: 40,
  username: 'Name 1',
  id: 'high'
},
{ value: 30,
  username: 'Name 2',
  id: 'low',
},
{ value: 60,
  username: 'Name 1',
  id: 'low',
},
{ value: 50,
  username: 'Name 2',
  id: 'high'
}]

I want to compare the objects with the same username key and return false where the object has the property id: low and its value is higher than any corresponding object with its id set to high.

So for this object false would be returned because the third object has the low for its id and it has a higher value than the corresponding object with the same username with high in its id.

Currently I'm filtering the array into two separate arrays like so.

    const higherTest = test.filter(item => item.id === 'high');
    const lowerTest = test.filter(item => item.id === 'low');

And then compare both using a nested for loop but this seems excessive and I am wondering if there is a cleaner way?

Upvotes: 0

Views: 50

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386560

You could take a hash table for visited names and store the low and height value. If a pair is found check the values and return the result of the check.

This approach uses a short circuit and returns for the first found low > high condition.

var data = [{ value: 40, username: 'Name 1', id: 'high' }, { value: 30, username: 'Name 2', id: 'low' }, { value: 60, username: 'Name 1', id: 'low' }, { value: 50, username: 'Name 2', id: 'high' }],
    result = !data.some((m => ({ value, username, id }) => {
        const user = m[username] = m[username] || {};
        user[id] = value;
        return 'high' in user && 'low' in user && user.low > user.high;
    })({}));

console.log(result);

Upvotes: 1

Related Questions