Determine the total number of unique items in an array, disregarding any duplicates

Looking for a JavaScript function that can count the unique items in an array by ignoring duplicates? Take this example,

var arr = [car, car, bike, bike, truck]

Instead of 5, the result should be 3.

Answer №1

Check out this solution:

let items = ['apple', 'apple', 'banana', 'banana', 'orange'];
let uniqueItems = [], count = 0, index = 0;
for(index=0; index<items.length; index++) {
    if(uniqueItems[items[index]] == undefined) {
        uniqueItems[items[index]] = 1;
        count++;
    }
}
console.log(count);

This code snippet counts the number of distinct elements in an array.

Answer №2

function findUniqueItems(arr) {
    var uniqueArr = [];
    for (i = arr.length; i--;) {
        if (uniqueArr.indexOf( arr[i] ) == -1) uniqueArr.push( arr[i] );
    }
    return uniqueArr.length;
}

utilized

var items = ['apple', 'orange', 'banana', 'apple'],
    uniqueCount = findUniqueItems(items);

FIDDLE

Answer №3

To find unique elements in an array, use the Array.filter() method.

var fruits = ['apple', 'banana', 'apple', 'orange'],
    uniqueFruits = fruits.filter(function(item, index, self) {
        return index === self.indexOf(item);
    });
console.log(uniqueFruits); // Output: ["apple", "banana", "orange"]

If you want to make this function available for all arrays:

Array.prototype.uniqueElements = function() {
    return this.filter(function(item, index, self) {
        return index === self.indexOf(item);
    });
};

Usage:

fruits.uniqueElements(); // Output: ["apple", "banana", "orange"]

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble in React.js when trying to run `npm start` with an

Upon initially building a todo app in react.js by using the command: npx create-react-app app_name When I proceeded to run the command npm start, it resulted in displaying errors: https://i.sstatic.net/BxYFu.png https://i.sstatic.net/EqU1j.png In furth ...

value of object's property set to string "null" if null

I am facing an issue with my Angular app, where I am sending an object via a PUT request to my Express server. The request's content-type is multipart/form-data. The object structure is as follows: obj = { field1 : "foo", field2 : null } Upon ...

Updating reference documents when adding to an array within Express

In my database schema, I have a Candidate with references to an array of Endorser. Here is how it's set up: const CandidateSchema = new mongoose.Schema({ name: { type: String, required: true, trim: true }, endorsem ...

Creating personalized headers for WebSocket in JavaScript

I am currently in search of a straightforward method to utilize WebSocket with custom headers for a web application, utilizing PHP as the backend and js+vuejs for the frontend. My application needs to establish a connection with a WebSocket server based o ...

The for loop effectively populates the array with elements, but strangely returns an empty array afterwards

After spending all morning troubleshooting, I finally got this code to run successfully and add elements to the array. However, a perplexing issue arises when I try to return the array as it comes back empty. It's been a frustrating morning of debuggi ...

JavaScript's Array.map function failing to return a value

Here is a snippet of code from an api endpoint in nextJS that retrieves the corresponding authors for a given array of posts. Each post in the array contains an "authorId" key. The initial approach did not yield the expected results: const users = posts.ma ...

Unpredictable jQuery Ajax setTimeout

I have a script that retrieves data from ajax.php and displays it in a div. The intention is for the information to be shown for a period of 3 seconds before hiding the #ajax-content and displaying #welcome-content. Most of the time it works as intended, ...

How can I animate SVG paths to fade in and out sequentially?

My current code is causing the path to fade in/out all at once instead of one after the other var periodClass = jQuery(this).parent().attr("class"); jQuery("svg path").each(function(i) { var elem = jQuery(this); if (elem.hasClass(periodClass)) ...

Start numerous nodejs servers with just a single command

I currently have multiple Nodejs servers, each stored in its own separate folder within a root directory. Whenever I need to run these servers, I find it cumbersome to navigate through each folder and manually type nodemon *name*. The number of servers i ...

How to use jQuery to trigger multiple divs having the same class

Using the Cycle 2 plugin, I have this code snippet currently: jQuery(function($){ $('.cycle-slideshow').cycle('pause'); $('.cycle-slideshow').hover(function () { //mouse enter - Resume the slideshow $('.cycle-sli ...

Update the URL for Product Details upon Color selection in ASP.NET Core

I'm currently working on an E-commerce platform focusing on Laptops. My goal is to enable users to seamlessly switch between different laptop colors by simply selecting a color from the dropdown menu, which should then redirect them to the product pag ...

What is the syntax for linking to a different file in the frontmatter of a markdown file?

Currently, I am in the process of setting up Astro's Content Collections. One particular task I would like to achieve is referencing a specific author from my `authorCollection` within an article. In attempting to accomplish this, I considered utiliz ...

"Is there a way to retrieve the CSS of all elements on a webpage by providing a URL using

Currently, I am in the process of creating a script that can crawl through all links provided with a site's URL and verify if the font used on each page is helvetica. Below is the code snippet I have put together (partially obtained online). var requ ...

Encountering issues with innerHTML displaying undefined results while trying to retrieve and showcase data from a database through the use

This is a sample script for fetching data from a database using AJAX. <!DOCTYPE html> <html> <head> <script type="text/javascript"> function loadJSON() { var data_file = "http://www.example.com/data/connect.php"; var xmlhttp; ...

Adjusting the letter spacing of individual characters using HTML and CSS

Is there a way to set letter-spacing for each character with different sizes as the user types in a text box? I attempted to use letter-spacing in CSS, but it changed all characters to the same size. Is there a possible solution for this? Here is the code ...

Steps to activate a faded background following a form submission triggered by an On change event

My goal is to implement a greyed-out background upon form submission without a traditional submit button. Instead, I want the form to be submitted when the user selects an option from one of three drop-down lists. Here is a snippet of the form: <form ...

What methods can be used to indicate the source of a GET request in a protocol?

When I request "/home" and specify that home.html should be served, I want to define the location from which all the resources included in home.html should be retrieved. For instance, if my file system looks like this: -public -home.html -home ...

Getting started with arrays: A beginner's guide

Greetings and thank you for taking the time to read my post today! I am relatively new to the world of programming, but I have been diving into various online courses and exploring javascript and nodejs in recent weeks. The array below is a crucial compon ...

What steps can be taken to troubleshoot issues with the jquery mask plugin?

I am using the jQuery Mask Plugin available at to apply masks to input fields on my website. Currently, I am trying to implement a mask that starts with +38 (0XX) XXX-XX-XX. However, I am facing an issue where instead of mandating a zero in some places, ...

The AJAX script data-type fails to function properly when making cross domain requests

Below is the code snippet I am using: $.ajax({ method: "POST", url: "http://phpseverdomain/dynamic.php", dataType: "script", data: { type: "2" } }) PHP Code: <?php header("Access-Control-Allow-Origin: *"); header("Access-Cont ...