Today I Learned - Rocky Kev

TIL Eliminating duplicate objects

POSTED ON:

TAGS:

Using Set datatypes can let you do this with no fuss.

const values = ['jane', 'lars', 'jane'];
const uniqueValues = [...new Set(values)]; // ['jane', 'lars'];

But you can't do this with arrays that have objects inside of it.

Set would consider each object to be unique.

const members = [
{
first: 'Jane',
last: 'Bond',
id: '10yejma',
},
{
first: 'Lars',
last: 'Croft',
id: '1hhs0k2',
},
{
first: 'Jane',
last: 'Bond',
id: '1y15hhu',
},
];

Solutions would be to:

Approach 1: Building a new Array without duplicates

You can create a helper function that compares a specific key, and add them only if they don't exist.

const uniqueMembers1 = [];

for (const m of members) {
if (!containsMember(uniqueMembers1, m)) {
uniqueMembers1.push(m);
}
}

function containsMember(memberArray, member) {
return memberArray.find(
(m) => m.first === member.first && m.last === member.last);
}

Approach #2: using filter

// Only keep members m if they appear for the first time
const uniqueMembers2 = members.filter(
(m, index, ms) => getIndexOfMember(ms, m) === index);

function getIndexOfMember(memberArray, member) {
return memberArray.findIndex(
(m) => m.first === member.first && m.last === member.last);
}

Approach #3: Map from unique keys to members


const uniqueKeyToMember = new Map(
members.map(m => [m.first+'\t'+m.last, m])); // [key, value]

const uniqueMembers3 = [...uniqueKeyToMember.values()];

Via Eliminating duplicate objects: three approaches


Related TILs

Tagged:

TIL what is npm Script

Despite their high usage they are not particularly well optimized and add about 400ms of overhead. In this article we were able to bring that down to ~22ms.

TIL fancy methods to transform Javascript Objects

You can use Object.entries(), Object.keys(), Object.fromEntries()...

TIL how to hide your JS code

ONE THING TO NOTE: Encrypting a script is stronger than obfuscation, both methods are still not adequate to protect secret content. Honestly, I don't think it's worth it on a production site, and instead just go with pure server-side if you want security. But it's fascinating.