javascript - find unique objects in array based on multiple properties
You could build a combined key for the hash table and filter the given array.
var arr = [{ class: "second", fare: "a" }, { class: "second", fare: "b" }, { class: "first", fare: "a" }, { class: "first", fare: "a" }, { class: "second", fare: "a" }, { class: "first", fare: "c" }],
result = arr.filter(function (a) {
var key = a.class + '|' + a.fare;
if (!this[key]) {
this[key] = true;
return true;
}
}, Object.create(null));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
The same without (mis)using thisArg
of Array#filter
.
var array = [{ class: "second", fare: "a" }, { class: "second", fare: "b" }, { class: "first", fare: "a" }, { class: "first", fare: "a" }, { class: "second", fare: "a" }, { class: "first", fare: "c" }],
seen = Object.create(null),
result = array.filter(o => {
var key = ['class', 'fare'].map(k => o[k]).join('|');
if (!seen[key]) {
seen[key] = true;
return true;
}
});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Using a combined key and a Map
const array = [
{ class: "second", fare: "a" },
{ class: "second", fare: "b" },
{ class: "first", fare: "a" },
{ class: "first", fare: "a" },
{ class: "second", fare: "a" },
{ class: "first", fare: "c" }
];
console.log(unique(array, ['class', 'fare']));
function unique(arr, keyProps) {
const kvArray = arr.map(entry => {
const key = keyProps.map(k => entry[k]).join('|');
return [key, entry];
});
const map = new Map(kvArray);
return Array.from(map.values());
}
short way to solve the above problem though it is a very old thread and maybe it might help someone in the future.
const array = [
{ class: "second", fare: "a" },
{ class: "second", fare: "b" },
{ class: "first", fare: "a" },
{ class: "first", fare: "a" },
{ class: "second", fare: "a" },
{ class: "first", fare: "c" }
];
const uniqueObjects = new Set();
array.forEach(arr => uniqueObjects.add(JSON.stringify(arr)));
console.log(uniqueObjects.entries())