Filter Unique Array Values Based on Function

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will learn how to create an array with unique values filtered out based on a comparator function in JavaScript. We will use the Array.prototype.filter() and Array.prototype.every() methods to create an array containing only the non-unique values. This lab will provide hands-on experience in filtering unique array values using a comparator function.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/BasicConceptsGroup -.-> javascript/obj_manip("`Object Manipulation`") javascript/AdvancedConceptsGroup -.-> javascript/higher_funcs("`Higher-Order Functions`") subgraph Lab Skills javascript/variables -.-> lab-28336{{"`Filter Unique Array Values Based on Function`"}} javascript/data_types -.-> lab-28336{{"`Filter Unique Array Values Based on Function`"}} javascript/arith_ops -.-> lab-28336{{"`Filter Unique Array Values Based on Function`"}} javascript/comp_ops -.-> lab-28336{{"`Filter Unique Array Values Based on Function`"}} javascript/obj_manip -.-> lab-28336{{"`Filter Unique Array Values Based on Function`"}} javascript/higher_funcs -.-> lab-28336{{"`Filter Unique Array Values Based on Function`"}} end

Filter Unique Array Values Based on Function

Here's how to create an array that contains only the non-unique values by filtering out the unique ones based on a comparator function, fn:

const filterUniqueBy = (arr, fn) =>
  arr.filter((v, i) => arr.some((x, j) => (i !== j) === fn(v, x, i, j)));

To use this function, call filterUniqueBy() with two arguments: the array you want to filter and the comparator function. The comparator function should take four arguments: the values of the two elements being compared and their indexes.

For example, if you have an array of objects and you want to filter out the objects with unique id values, you can do this:

filterUniqueBy(
  [
    { id: 0, value: "a" },
    { id: 1, value: "b" },
    { id: 2, value: "c" },
    { id: 3, value: "d" },
    { id: 0, value: "e" }
  ],
  (a, b) => a.id == b.id
); // [ { id: 0, value: 'a' }, { id: 0, value: 'e' } ]

To start practicing coding, open the Terminal/SSH and type node.

Summary

Congratulations! You have completed the Filter Unique Array Values Based on Function lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like