Reputation: 948
i have an object
{eno: Object, sc: Object, r: Object}
each nested Object contain array example
{
eno :{data:[0,'a','b','3']},
sc:{data:[0,'a','b','3','f','l']},
r:{data:[0,'a','b','3','p']},
}
the element of each object is dynamic how can i get same value of each data array element
same value = [0,'a','b','3']
and if there not any same element some value ='nope'
Upvotes: 0
Views: 60
Reputation: 10366
You can use intersection
function from Lodash
:
var _ = require('lodash');
var sameElements = _.intersection(eno.data, sc.data, r.data);
Upvotes: 0
Reputation: 16226
As @Alberto Trindade Tavares' answer said, intersection of lodash can be used to get the same value easily, the code would be very clean. @Alberto Trindade Tavares' answer does not provide a code snippet, and also does not handle the "nope" logic when there is no same value. Thus, I'd like to post a working code snippet as below:
var obj = {
eno :{data:[0,'a','b','3']},
sc:{data:[0,'a','b','3','f','l']},
r:{data:[0,'a','b','3','p']},
}
var sameVal = _.intersection(obj.eno.data, obj.sc.data, obj.r.data);
var sameValDisplay = 'Nope';
if (sameVal.length > 0) {
sameValDisplay = sameVal.toString();
}
console.log('Same value is: ' + sameValDisplay);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
Upvotes: 1
Reputation: 22534
var commonElements = function(array1, array2) {
return array1.filter(function(n) {
return array2.indexOf(n) !== -1;
});
}
var obj = {
eno :{data:[0,'a','b','3']},
sc:{data:[0,'a','b','3','f','l']},
r:{data:[0,'a','b','3','p']},
};
var result = commonElements(obj.eno.data, commonElements(obj.sc.data, obj.r.data)) || 'nope';
console.log('same value :' + result);
/* Solution using map, reduce and filter*/
var res = Object.keys(obj)
.map( o => obj[o].data)
.reduce((a, b) => a.filter(c => b.includes(c)));
console.log('same value :' + res|| 'nope');
Upvotes: 1