Rey Something Rey Something - 4 months ago 15
Javascript Question

Try to compare keys in an array of objects

I need to loop into this array and compare the value of the object that is in the array but I have try different methods and I can get it. am i missing something or is there a better way to do it?

var all = [{a: 1, b: 2, c: 9, d: 5}, {a: 1, t: 58, r: 19, d: 5}, {a: 1, t: 14, r: 89, d: 5}];

for (var i = 0; i < all.length; i++) {
for (var j = 0; j < all.length; j++) {
for(var key in i){
for(var keyz in j){
if(all[i][key] != all[j][keyz]){
console.log('no same');
}
}
}
}
}

Answer

Try this:

var all = [{a: 1, b: 2, c: 9, d: 5}, {a: 1, t: 58, r: 19, d: 5}, {a: 1, t: 14, r: 89, d: 5}];
    var output = [], tempObj = {};
    for (var i = 0; i < all.length; i++) {
        var object =  all[i];
        for(var key in object) {
            if(tempObj[key] && tempObj[key].value == object[key]) {
                delete output[tempObj[key].index][key];
                delete object[key];
            } else {
                tempObj[key] = {
                    value: object[key],
                    index: i
                }
            }
        }
        output[i] = object;
    }
    console.log(output)

Comments