I have an array of dynamic objects like that:
var arr = [
{state: "FL"},
{state: "NY"},
{state: "FL"},
{gender: "Male"},
{state: "NY"},
{gender: "Female"},
{gender: "Female"},
{year: "1990"}
]
How can I get just the unique objects?
The desired output is an array containing just the unique objects:
arr = [
{state: "FL"},
{state: "NY"},
{gender: "Male"},
{gender: "Female"},
{year: "1990"}
]
I'm trying something like that using reduce, but on this way I need know the object key:
arr = arr.reduce((acc, curr) =>
acc.find(e => e['state'] === curr['state']) ? acc : [...acc, curr], [])
It's not a duplicate because the other questions does not use "dynamic object" to get unique
One way to get distinct values from an array of JavaScript objects is to use the array's map method to get an array with the values of a property in each object. Then we can remove the duplicate values with the Set constructor. And then we can convert the set back to an array with the spread operator.
You could stringify all objects, get the unique JSON and then convert the strings back to objects.
var array = [{ state: "FL" }, { state: "NY" }, { state: "FL" }, { gender: "Male" }, { state: "NY" }, { gender: "Female" }, { gender: "Female" }, { year: "1990" }],
unique = Array.from(
new Set(array.map(o => JSON.stringify(o))),
s => JSON.parse(s)
);
console.log(unique);
.as-console-wrapper { max-height: 100% !important; top: 0; }
If you have more than one key in the object and because if you have objects where the keys are in different order, I suggest you to get the entries first, sort this array, stringify it for a set, and then get the new objects back.
var array = [{ foo: 42, state: "FL" }, { state: "FL", foo: 42 }, { state: "FL" }, { state: "NY" }, { state: "FL" }, { gender: "Male" }, { state: "NY" }, { gender: "Female" }, { gender: "Female" }, { year: "1990" }],
unique = Array.from(
new Set(array.map(o => JSON.stringify(Object.entries(o).sort(([a], [b]) => a.localeCompare(b))))),
s => Object.assign({}, ...JSON.parse(s).map(([k, v]) => ({ [k]: v })))
);
console.log(unique);
.as-console-wrapper { max-height: 100% !important; top: 0; }
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