Introduction
In this lab, we will explore how to use the uniqueElementsByRight() function in JavaScript to find the reversed unique values of an array based on a provided comparator function. We will learn how to use Array.prototype.reduceRight() and Array.prototype.some() methods to create an array containing only the last unique occurrence of each value based on the comparator function provided. By the end of this lab, you will have a better understanding of how to manipulate arrays in JavaScript using these methods.
Function to Find Reversed Unique Values in Array
To find all the unique values of an array based on a provided comparator function from the right, follow these steps:
- Open the Terminal/SSH and type
nodeto start practicing coding. - Use
Array.prototype.reduceRight()andArray.prototype.some()to create an array containing only the last unique occurrence of each value, based on the comparator functionfn. - The comparator function takes two arguments: the values of the two elements being compared.
- Here's the code to implement the function:
const uniqueElementsByRight = (arr, fn) =>
arr.reduceRight((acc, v) => {
if (!acc.some((x) => fn(v, x))) acc.push(v);
return acc;
}, []);
- Use the following code to test the function:
uniqueElementsByRight(
[
{ id: 0, value: "a" },
{ id: 1, value: "b" },
{ id: 2, value: "c" },
{ id: 1, value: "d" },
{ id: 0, value: "e" }
],
(a, b) => a.id == b.id
); // [ { id: 0, value: 'e' }, { id: 1, value: 'd' }, { id: 2, value: 'c' } ]
Summary
Congratulations! You have completed the Reversed Unique Values in Array Based on Function lab. You can practice more labs in LabEx to improve your skills.