Imo Imo - 3 months ago 9
AngularJS Question

How to compare arrays where the values inside objects have diffrent sequence javascript

I have two arrays where I would like to find matching values inside arrays. But these values occur in different sequence. How can I compare these values in plain JavaScript. I want to match the values of propert1 and name and then extract property3 where property1 matches name

code:

var data = []
var data1 = [
{'property1': 'john', 'property2': 12},
{'property1': 'jasmin', 'property2': 22},
{'property1': 'dog', 'property2': 22}
]
var data2 = [
{'name': 'dog', 'property2': 12, 'property3': 'xys'},
{'name': 'john', 'property2': 22, 'property3': 'acb'},
{'name': 'jasmin', 'property2': 22, 'property3': 'jjj'}
]

for(var i=0; i<data1.length; i++){
if(data1[i].property1 == data2[i].name){
data.push({
'property1': data1[i].property1,
'property2': data1[i].property2,
'property3': data2[i].property3
})
} else {
console.log('not equal')
}
}


jsfiddle

expected output

data=[{'property1': 'john', 'property2': 12, 'property3': 'acb'},
{'property1': 'jasmin', 'property2': 22, 'property3': 'jjj'},
{'property1': 'dog', 'property2': 22, 'property3': 'xys'}]

Answer

var data = []
var data1 = [
    {'property1': 'john', 'property2': 12}, 
    {'property1': 'jasmin', 'property2': 22}, 
    {'property1': 'dog', 'property2': 22}
];
var data2 = [
    {'name': 'dog', 'property2': 12, 'property3': 'xys'}, 
    {'name': 'john', 'property2': 22, 'property3': 'acb'}, 
    {'name': 'jasmin', 'property2': 22, 'property3': 'jjj'}
];

data = data1.slice().map(function(el){
    for (var i = 0, l = data2.length; i < l; i++) {
        if (el.property1 === data2[i].name) {
            el.property3 = data2[i].property3;
        }
    }
    return el;
});

console.log(data);

data1.slice().map(...) works on a copy of the original array, so in the loop we don't alter original data.

Comments