Search code examples
javascriptjquerybackbone.jsunderscore.js

How to compare a property value in multiple objects of an array?


How can I compare a property value in multiple objects of an array? I have a few objects in array x.

var arr = [{a:1, b:2, c:3, d:4}, {a:1, x:2, y:3, z:4}, ...]

I want to compare and return true if the value of 'a' is same in all the objects in the array


Solution

  • For checking if all objects contains for the same key the same value, you could use a destructuring assignment for getting the first item and check against the actual item.

    var array = [{ a: 1, b: 2, c: 3, d: 4 }, { a: 1, x: 2, y: 3, z: 4 }],
        key = 'a';
    
    console.log(array.every((a, _, [b]) => a[key] === b[key]));

    Taking a substring for compairing

    var array = [{ a: 12345, b: 2, c: 3, d: 4 }, { a: 12367, x: 2, y: 3, z: 4 }];
    
    console.log(array.every((a, _, [b]) => a.a.toString().slice(0, 3) === b.a.toString().slice(0, 3)));

    ES5

    var array = [{ a: 12345, b: 2, c: 3, d: 4 }, { a: 12367, x: 2, y: 3, z: 4 }];
    
    console.log(array.every(function (a, _, b) {
        return a.a.toString().slice(0, 3) === b[0].a.toString().slice(0, 3);
    }));