Verify whether the element appears twice in the array

Is there a way to determine if an element appears more than once in an array?

var arr = [elm1, elm2, elm3, elm3, elm4, elm5, elm5, elm5, elm6, elm7];
if (elm appears multiple times in the array) {
      // code to be executed
} else {
      // do something else
}

Any ideas on how to achieve this?

Answer №1

If you're looking for a way to count occurrences in an array, the countInArray function could be a helpful option.

function countInArray(array, what) {
    return array.filter(item => item == what).length;
}

Alternatively, you may find this approach more straightforward and easier to customize:

var list = [2, 1, 4, 2, 1, 1, 4, 5];  

function countInArray(array, what) {
    var count = 0;
    for (var i = 0; i < array.length; i++) {
        if (array[i] === what) {
            count++;
        }
    }
    return count;
}

countInArray(list, 2); // returns 2
countInArray(list, 1); // returns 3

Answer №2

function checkForDuplicates(){
var arr =['1','2','3','3','4'];
  for (i=0; i<arr.length;i++){
    for (x=0;x<arr.length;x++){
      if(arr[i]==arr[x] && i != x){
        console.log('Duplicate element in array: '+arr[i]);
      }else console.log('No duplicates found');
    }
  }
}

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

The view has no access to $scope but the controller does

I need to display the iso code using a $scope when selecting a country from a list. The list of countries is fetched through a $http call in a factory and then stored in a scope. ///////// get countries //////////////// tableFactory.getCountries().then(f ...

The Bootstrap accordion feature or show/hide function is experiencing issues when dealing with dynamically created elements in jQuery

When interacting with items in my sample application, a pop-up displaying the item's description should appear. However, attempts to use Bootstrap accordion or hide and show features were unsuccessful, only jQuery delegate event handlers worked. In g ...

Select multiple options by checking checkboxes in each row using React

Is it possible to display multiple select checkboxes with more than one per row? For example, I have four options [a, b, c, d]. How can I arrange it to have 2 options per row, totaling 2 rows instead of having 1 option per row for 4 rows? ☑a ☑b ☑c ...

Retrieving the data stored in a key of a JSON reply

What is the correct way to retrieve the value of the key "exists" from the json response? I have attempted the following methods: $json['data']['exists'] and $json['data']->exists however, neither of them seem to be work ...

Generate a dynamic form that automatically populates different input fields based on JSON data

I am trying to dynamically auto populate a form with various input types such as select boxes and text areas. I have successfully implemented this for input boxes, see example below: function autofill(){ var data = [{visible_retail: "0", brand: ...

The window.addEventListener function is failing to work properly on mobile devices

Hey there! I am facing an issue in my JS code. I wrote this code because I want the menu to close when a visitor clicks on another div (not the menu) if it is open. The code seems to be working fine in developer tools on Chrome or Firefox, but it's no ...

Slideshow elements removed

I attempted to remove my links individually from the div id="wrapper", but unfortunately have encountered an issue while doing so: window.onload = function () { setInterval(function () { var wrapper = document.getElementById("wrapper"); var my_l ...

Issue with npm installation leading to missing node_modules directory

When attempting to run npm install . in a local directory, I keep encountering the following errors: npm ERR! install Couldn't read dependencies npm ERR! Darwin 15.2.0 npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "install" "." npm ERR! no ...

Changing the background color of a page to match the background color of a button in React, which can be updated at any time

I have a special button called ArbitraryBtn that, when clicked, changes the page's background color to random colors: import React from 'react'; export const changeToArbitraryColor = () => (document.body.style.backgroundColor = ...

JavaScript Error Caused by Newline Characters

I'm facing an issue with extracting data from a textbox using JavaScript. What I'm attempting to do is retrieve the value from a textbox, display it in an alert, and then copy it. Here's the current code snippet: var copyString = "Date: < ...

Passing a variable through jQuery onClick event to a URL via GET request and subsequently loading the content of

After successfully passing variables through AJAX calls via onClick to a PHP file and loading the results on the initial page, I now face the challenge of passing a variable analogously via onClick to a PHP file but this time I need to either open a new wi ...

Creating a glowing shimmer using vanilla JavaScript

After successfully creating the Shimmer Loading Effect in my code, I encountered a hurdle when trying to implement it. The effect is visible during the initial render, but I struggle with utilizing it effectively. The text content from my HTML file does no ...

Vertical positioning offset of jQuery UI selectmenu in relation to buttons on this line

When creating a form, I like to place control elements in a line such as a button, select box, and checkbox for a logical layout. However, after incorporating jQuery UI, I noticed a strange vertical alignment issue with the select box. For reference, here ...

What is the best method for disseminating data to multiple stores with just a single action in the React flux architecture?

Is there a way to efficiently update multiple stores with data in one action? Imagine receiving post data from a server as a user action. Below is a simple pseudo code for this action: class UserActions { getPosts() { asyncFetch(apiEndPoint, ...

Maintain the newly selected background color for the current day in fullcalendar when navigating to the next or previous month

Currently, I am working on a project in React using npm fullcalendar. One of the requirements is to change the color of the current day. After some trial and error, I was able to achieve this by adding the following code: $('.fc-today').attr(&ap ...

Implementing a return of a view from a Laravel controller function after an AJAX request

I'm currently working on a bookstore project where users can add books to their cart. Users have the option to select multiple books and add them to the cart. When the user clicks on the Add to Cart button, I store the IDs of the selected books in a J ...

Guide on inserting text within a Toggle Switch Component using React

Is there a way to insert text inside a Switch component in ReactJS? Specifically, I'm looking to add the text EN and PT within the Switch Component. I opted not to use any libraries for this. Instead, I crafted the component solely using CSS to achie ...

How can strings of dates be arranged in MM/DD/YYYY order?

Is there a correct way to sort these dates in descending order? I've attempted using arr.sort() and arr.sort().reverse(), searched extensively on stack overflow, but still cannot find a solution. Every attempt at sorting them seems to be incorrect. [ ...

What steps should I take to set up a personalized prompt for user input in AngularJS?

After setting up the UI and scope variables, I am faced with a task that requires the function to only continue when either the left or right button is clicked (meaning $scope.isLeft or $scope.isRight will be true). This behavior is akin to how a regular J ...

Implement an AJAX function to prompt a save dialog before initiating the download process

I'm currently programming an embedded device in C with a web server. One of the tasks I am working on is downloading files from this device. I need to download several files at once, so I've set up an AJAX request that uses a POST method and send ...