I have an array of objects:
var arr = [
0: {a: ["ram", "shyam", "kunal"], b: ["abc", "xyz", "wxd"], c: ["nyx", "lux", "poc"]},
1: {d: ["ry", "cd", "er"], e: ["ew", "op", "re", "er"], c:["er", "sd", "we"]},
2: {a: ["we", "as"], e: ["we", "lk", "pm"], c:["cv", "as", "xc"]}
]
I am getting an array of objects and I need to find out the matched key that is common in all objects: for example here c is common in all the 3 objects. So I need c with the values in all 3. There is a high possibility that there can be more than 3 objects in an array, it can be 4 or 5. In that case how to match the key and put their values in one array?
output: key c :["nyx", "lux", "poc", "er", "sd", "we", "cv", "as", "xc"];
I am able to get a match for 2 but am facing difficulties finding when the comparison is more than 2.
js:
for (var i = 0; i < ar.length; i++) {
for (var key in arr[0]) {
if (i > 0) {
if (arr[i].hasOwnProperty(key)) {
arr[0][key].push(...arr[i][key]);
}
}
}
}
This only works for 2 objects comparison.
4
Answers
You can use array reduce with with a
Map
and at the end domap.get('c')
Here’s a function when supplied a specific key:
Array#reduce
is used to accumulate all values where the object contains that key, using the spread operator to combine the original array and the current array.If you want to have an array with all keys at once:
Please try this way.