Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
71
rated 0 times [  72] [ 1]  / answers: 1 / hits: 43208  / 9 Years ago, mon, december 21, 2015, 12:00:00

I have two object literals like so:



var firstObject =
{
x: 0,
y: 1,
z: 2,

a: 10,
b: 20,
e: 30
}

var secondObject =
{
x: 0,
y: 1,
z: 2,

a: 10,
c: 20,
d: 30
}


I want to get the intersection of the keys these two object literals have like so:



var intersectionKeys  = ['x', 'y', 'z', 'a']


I can obviously do a loop and see if a key with the same name exists in the other object, but I am wondering if this would be a good case for some functional programming and map / filter / reduce usage? I myself have not done that much functional programming, but I have a feeling, that there could exist a clean and clever solution for this problem.


More From » object

 Answers
19

A solution without indexOf.





var firstObject = { x: 0, y: 1, z: 2, a: 10, b: 20, e: 30 },
secondObject = { x: 0, y: 1, z: 2, a: 10, c: 20, d: 30 };

function intersection(o1, o2) {
return Object.keys(o1).concat(Object.keys(o2)).sort().reduce(function (r, a, i, aa) {
if (i && aa[i - 1] === a) {
r.push(a);
}
return r;
}, []);
}

document.write('<pre>' + JSON.stringify(intersection(firstObject, secondObject), 0, 4) + '</pre>');





Second attempt with O(n).





var firstObject = { x: 0, y: 1, z: 2, a: 10, b: 20, e: 30 },
secondObject = { x: 0, y: 1, z: 2, a: 10, c: 20, d: 30 };

function intersection(o1, o2) {
return Object.keys(o1).filter({}.hasOwnProperty.bind(o2));
}

document.write('<pre>' + JSON.stringify(intersection(firstObject, secondObject), 0, 4) + '</pre>');




[#63992] Friday, December 18, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kiyam

Total Points: 448
Total Questions: 96
Total Answers: 92

Location: Philippines
Member since Sat, Jul 11, 2020
4 Years ago
;