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.
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.
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.
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);
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"]
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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, ...
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)) ...
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 ...
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 ...
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 ...
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 ...
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 ...
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; ...
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 ...
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 ...
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 ...
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 ...
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, ...
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 ...