3

In the given object all values of properties are the same.

var obj = {
    property1: 'Some Value',
    property2: 'Some Value',
    property3: 'Some Value',
    property4: 'Some Value'
}

The function checkEquality should return true if all values are the same and false otherwise.

I can do the following to achieve it:

function checkEquality () {
    var compare = obj.propery1;

    for (var key in obj) {
        if (obj[key] !== compare) {
            return false;
        }
    }

    return true;
}

But this solution by far not the best.

2 Answers 2

4

You could use Array#every for it.

The every method executes the provided callback function once for each element present in the array until it finds one where callback returns a falsy value (a value that becomes false when converted to a Boolean). If such an element is found, the every method immediately returns false. Otherwise, if callback returned a true value for all elements, every will return true. callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values.

var obj = { propery1: 'Some Value', propery2: 'Some Value', propery3: 'Some Value', propery4: 'Some Value' },
    equal = Object.keys(obj).every(function (k, i, kk) {
        return !i || obj[kk[0]] === obj[k];
    });

console.log(equal);

Sign up to request clarification or add additional context in comments.

1 Comment

I think using .some to find whether any element is different would be more optimal, since it would terminate on the first difference, thus going over every element would only be a worst-case scenario.
1

Great answer by @Nina, I'd just like to add something different using reduce and ES6 syntax:

const sameValues = (obj ) => {
    let keys = Object.keys( obj );
    let initial = obj[ keys[0] ];
    // val will be either the initial value or false
    let val = keys.reduce( (prev, cur) => ( obj[cur] === prev ? prev : false ), initial ); 
    return val === initial;
}

https://jsfiddle.net/9tb5mdoL/

2 Comments

but reduce does not stop, if false. what if false is a value to test for?
1. I know :) I have commented on your answer fully aware of this disadvantage of my approach. 2. See the linked fiddle (false === false)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.