JavaScript array of objects contains the same array data
You could map data
and get the common values with Array#map
, Array#reduce
, Array#filter
, Set
and Set#has
.
var array = [{ name: "Foo", id: "123", data: ["65d4ze", "65h8914d"] }, { name: "Bar", id: "321", data: ["65d4ze", "894ver81"] }],
key = 'data',
common = array
.map(o => o[key])
.reduce((a, b) => b.filter(Set.prototype.has, new Set(a)));
console.log(common);
You can use the Array#filter
method. Filter the first array by checking if a value is present in all other object properties (arrays), using the Array#every
method to check if a value is present in all remaining arrays.
let res = a[0].data.filter(v => a.slice(1).every(a => a.data.includes(v)));
var a = [{
name: "Foo",
id: "123",
data: ["65d4ze", "65h8914d"]
},
{
name: "Bar",
id: "321",
data: ["65d4ze", "894ver81"]
}
];
let res = a[0].data.filter(v => a.slice(1).every(a => a.data.includes(v)));
console.log(res)