I have following array:
[
{name: "Joske", code: "IEDDK"},
{name: "Mieke", code: "IEDDK"},
{name: "Jan", code: "IEDDK"},
{name: "Test", code: "IsxJK"},
{name: "Koen", code: "IsxJK"},
]
And I need a function which gives me an array of objects where there is only once occurrence of the code property:
[
{name: "Joske", code: "IEDDK"},
{name: "Test", code: "IsxJK"},
]
I have thought about it and I think I'm making it harder than it needs to be. Does someone has a simple function to do this?
If you don't mind a "last wins", this can be done nicely with
[...new Map(data.map(d => [d.code, d])).values()]
with O(n) complexity (unlike some other approaches that re-iterate the array for every member, looking for matches thereby exhibiting quadratic complexity).
For a "first wins", just reverse your data:
[...new Map([...data].reverse().map(d => [d.code, d])).values()]
This can be folded into a typesafe generic function:
const distinctBy = <T, K>(data: T[], keySelector: (v: T) => K): T[] =>
[...new Map(data.map(d => [keySelector(d), d])).values()]
and used
distinctBy(data, d => d.code)
With filter and findIndex is also an option:
const arr = [
{name: "Joske", code: "IEDDK"},
{name: "Mieke", code: "IEDDK"},
{name: "Jan", code: "IEDDK"},
{name: "Test", code: "IsxJK"},
{name: "Koen", code: "IsxJK"},
];
const isTheSameAs = ({ code }) => item => item.code === code;
const filteredArr = arr
.filter((item, indexInOriginalArray, array) => array.findIndex(isTheSameAs(item)) === indexInOriginalArray);
console.log(filteredArr);
Group your array based on code using array#reduce in an object accumulator and extract all the values using Object.values().
const data = [{ name: "Joske", code: "IEDDK" }, { name: "Mieke", code: "IEDDK" }, { name: "Jan", code: "IEDDK" }, { name: "Test", code: "IsxJK" }, { name: "Koen", code: "IsxJK" }, ],
result = Object.values(data.reduce((r, o) => {
r[o.code] = r[o.code] || o;
return r;
},{}));
console.log(result);