Introduction
In this lab, we will explore a JavaScript function that filters non-unique array values based on a provided comparator function. By using Array.prototype.filter() and Array.prototype.every(), we will create a new array that contains only the unique values based on the comparator function. This lab aims to improve your understanding of JavaScript array methods and how to use them to manipulate data.
Filtering Non-Unique Array Values with a Function
To start practicing coding, open the Terminal/SSH and type node.
This code filters out non-unique values from an array, based on a provided comparator function. Here are the steps to achieve this:
- Use
Array.prototype.filter()andArray.prototype.every()to create a new array with only the unique values based on the comparator functionfn. - The comparator function takes four arguments: the values of the two elements being compared and their indexes.
- The function
filterNonUniqueByimplements the above steps and returns the unique values array.
const filterNonUniqueBy = (arr, fn) =>
arr.filter((v, i) => arr.every((x, j) => (i === j) === fn(v, x, i, j)));
Here is an example of how to use this function:
filterNonUniqueBy(
[
{ 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: 2, value: 'c' } ]
This code is concise, clear and coherent and should work as expected.
Summary
Congratulations! You have completed the Filter Non-Unique Array Values Based on Function lab. You can practice more labs in LabEx to improve your skills.