Comprehensive Guide to Using array-unique in JavaScript

Introduction to Array Unique Function in JavaScript

In programming, you often encounter scenarios where you need to remove duplicate entries from an array. The array-unique function helps you achieve this effectively in JavaScript. This guide will introduce you to the array-unique function and provide dozens of useful API explanations with code snippets.

Basic Usage

The most straightforward way to create a unique array is by using the Set object:

  
    const numbers = [1, 2, 2, 3, 4, 4, 5];
    const uniqueNumbers = [...new Set(numbers)];
    console.log(uniqueNumbers); // Output: [1, 2, 3, 4, 5]
  

Using Filter Method

You can also use the filter method to achieve the same result:

  
    const numbers = [1, 2, 2, 3, 4, 4, 5];
    const uniqueNumbers = numbers.filter((value, index, self) => self.indexOf(value) === index);
    console.log(uniqueNumbers); // Output: [1, 2, 3, 4, 5]
  

Custom Function to Remove Duplicates

If you want more control, you can create a custom function to remove duplicates:

  
    function arrayUnique(arr) {
      const result = [];
      for (const element of arr) {
        if (!result.includes(element)) {
          result.push(element);
        }
      }
      return result;
    }
    const numbers = [1, 2, 2, 3, 4, 4, 5];
    const uniqueNumbers = arrayUnique(numbers);
    console.log(uniqueNumbers); // Output: [1, 2, 3, 4, 5]
  

Handling Arrays with Objects

Removing duplicates from an array of objects requires a different approach:

  
    const users = [
      { id: 1, name: 'John' },
      { id: 2, name: 'Jane' },
      { id: 1, name: 'John' }
    ];
    const uniqueUsers = Array.from(new Set(users.map(user => JSON.stringify(user)))).map(str => JSON.parse(str));
    console.log(uniqueUsers); // Output: [{ id: 1, name: 'John' }, { id: 2, name: 'Jane' }]
  

App Example: Unique To-Do List

Let’s create a simple to-do list application that ensures no duplicate tasks are added:

  
    class TodoApp {
      constructor() {
        this.tasks = [];
      }

      addTask(task) {
        if (!this.tasks.includes(task)) {
          this.tasks.push(task);
          console.log(`Task "${task}" added.`);
        } else {
          console.log(`Task "${task}" is already in the list.`);
        }
      }

      getUniqueTasks() {
        return this.tasks;
      }
    }

    const myTodoApp = new TodoApp();
    myTodoApp.addTask("Learn JavaScript");
    myTodoApp.addTask("Read a book");
    myTodoApp.addTask("Learn JavaScript");  // Duplicate task
    console.log(myTodoApp.getUniqueTasks()); // Output: ['Learn JavaScript', 'Read a book']
  

In this application, the addTask method checks for duplicates before adding a new task, ensuring the to-do list remains unique.

By employing these methods, you can handle various scenarios where removing duplicates from arrays is necessary.

Hash: 6a8994bb4831d038dabf54f50197b8cb03fc5d5d70e92f9cc6f42669f527657f

Leave a Reply

Your email address will not be published. Required fields are marked *