I try to get all same data values into an array of objects. This is my input:
var a = [{
name: "Foo",
id: "123",
data: ["65d4ze", "65h8914d"]
},
{
name: "Bar",
id: "321",
data: ["65d4ze", "894ver81"]
}
]
I need a result like:
["65d4ze"]
I try to loop on my object to get this output, but I'm completely lost... I don't know how to know if the result is into all data arrays.
var a = [{
name: "Foo",
id: "123",
data: ["65d4ze", "65h8914d"]
},
{
name: "Bar",
id: "321",
data: ["65d4ze", "894ver81"]
}
],
b = [],
c = []
a.forEach(function(object) {
b.push(object.data.map(function(val) {
return val;
})
);
});
console.log(b);
Using the indexOf() method In this method, what we do is that we compare the index of all the items of an array with the index of the first time that number occurs. If they don't match, that implies that the element is a duplicate. All such elements are returned in a separate array using the filter() method.
Using includes() Method: If array contains an object/element can be determined by using includes() method. This method returns true if the array contains the object/element else return false. Example: html.
Use the in operator The in operator returns true if a property exists in an object. If a property does not exist in the object, it returns false . Unlike the hasOwnProperty() method, the in operator looks for the property in both own properties and inherited properties of the object.
We are required to write a function containsAll() that takes in two arguments, first an object and second an array of strings. It returns a boolean based on the fact whether or not the object contains all the properties that are mentioned as strings in the array.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With