A feature designed to determine the presence of duplicate numbers within an array

I'm attempting to develop a function that identifies duplicate numbers within an array and collects these duplicate numbers into a new array.

Here's the code I've come up with so far, but I'm encountering some challenges.

function findDuplicates(array) {
    var duplicates = [];
    for(var i = 0; i < array.length; i++) {
        if (array[i] === 1) {
            duplicates.push(array[i]);
        }
    }
    return duplicates;
}

alert(findDuplicates([1, 2, 3, 4, 5, 1]));




findDuplicates([2, 1, 1, 2, 2]); //Expected output: [1, 2, 2]. The original documents are 2, 1 and the copies are 1, 2, 2

Answer №1

indexOf is used to find the first occurrence index of an element within an array. On the other hand, filter iterates through each element in the array and creates a new array with elements for which a specified function returns true.

function solution(array) {
    return array.filter(function(value, index) {
        return array.indexOf(value) < index;
    });
}

Answer №2

Within your programming challenge, you have been given two arrays: one consisting of the original numbers and another containing the result where duplicate numbers are stored.

Your initial action of iterating over the original array shows a promising start.

The variable array[i] represents the current number in the original array.

To identify whether this current number is a duplicate that has already appeared, you will need to implement the next step into your algorithm.

This may require an additional loop, possibly another array, and most likely an 'if' statement incorporated somewhere within your solution.

Answer №3

An improved and quicker alternative to the initial solution:

const findDuplicates = (array) => {
   return array.filter((value, index) => {
      return array.indexOf(value, index + 1) !== -1;
   });
}

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

Using Rails: The Art of Safely Managing JavaScript code when working with AJAX on the client-side

How can I securely send a collection via to_json directly from the controller action to the client-side? When the request is sent from the controller action straight to the client-side without pre-processing, the process looks like this: An AJAX requ ...

pagination functionality incorporated into element ui tables

Issue with Element UI: when a checkbox is selected and the page is changed, the selected rows' checkboxes are removed. I need to retain the selection items while paging so that users can select items from multiple pages without losing the selections f ...

Issues with Read More/Less functionality on a website - Troubleshooting with JavaScript, jQuery, and Bootstrap 4

I'm looking to create a simple, lightweight feature where clicking on a "read more" link will reveal a paragraph, and then clicking on a "read less" link will hide it again. My knowledge of JS and JQuery is quite limited. I'm currently utilizing ...

Adjusting a NodeJS module for easier integration into codebases

I have organized some functions in a file within a node module structure... Here are the files and folder structure I created: - package.json - README.md - LICENSE.md - code |_______ code.js Currently, to use these functions, I include them like th ...

Repeated Identification Numbers in Mongoose Database

I have created a virtual object with a duplicated ID and I'm struggling to find a solution using the new syntax. Can anyone offer assistance? /** * Import only the mongoose in this class * This plugin is for MongoDB and this class decide how the Mon ...

Python: extract the decimal part of a floating-point number before the "e" exponent

Currently, I am utilizing Python for some mathematical calculations. At one point in the process, an array will be generated that appears like this: [1.23e-21, 2.32e-14, 8.87e-12, .....] My goal is to extract the values before the e.., meaning I want the ...

Retrieve HTML content from Vuetify components without displaying it on the webpage

I have a project where I need to retrieve the HTML code from various Vuetify components. Instead of just as a HTML string, I actually need it as a DOM element that can be easily added to the body. This is necessary for me to be able to utilize these compon ...

JQuery functionality not functioning properly following an AJAX page reload

Currently, I am utilizing a jQuery code to select all checkboxes in the following manner: var JQ7=jQuery.noConflict(); JQ7(document).ready(function(){ JQ7("#chkAll").click(function(){ JQ7(".chk").prop("checked",JQ7("#chkAll").prop("checked")) }) }); ...

Tips for bringing in specialized document formats in Typescript

For a fun side project, I am in the process of creating a "framework" to easily develop native web components. One aspect of this involves using a webpack loader to parse XML within custom .comp files and export an es2015 class. However, I've encounte ...

Is there a maximum number of window.open() calls that can be made in JavaScript?

Can the use of window.open("URL"); in JavaScript be limited? Upon attempting to open three windows using window.open("URL"), the third window did not open separately. Instead, it refreshed the contents of the first window and displayed the contents of ...

Is there a way to update multiple array object fields in a single request?

{ _id:xxxxstoreid store:{ products:[ { _id:xxxproductid, name:xxx, img:url, } ] } } As the request for update cannot be predicted, the params may contain on ...

When no items are available, the drag and drop functionality does not function

When I am performing drag and drop between two containers, everything functions correctly when there is at least one element present in the container. However, if I remove all elements from either container and try to drag them back, the operation fails. ...

What causes execution to halt without error in JavaScript?

While working with React hooks, I encountered an issue where code execution would inexplicably stop when reaching the await keyword within an async function. The await call is surrounded by a try...catch...finally block. Here's a simplified version of ...

Confusion surrounding the Javascript object prototype (utilizing require.js and three.js)

I'm feeling a bit confused about my understanding of Objects, prototypes, require.js and three.js. Let me illustrate with an example: In Summary: The instance "wee" is derived from "Wee," which acts as a wrapper or monkey patch for THREE... Shouldn& ...

Switching Next.js JavaScript code to Typescript

I am currently in the process of transforming my existing JavaScript code to TypeScript for a web application that I'm developing using Next.Js Here is the converted code: 'use client' import React, { useState, ChangeEvent, FormEvent } fro ...

Using Jquery to update the information displayed in a div class to show more details about the clicked video

I am currently developing a video playlist similar to YouTube for my hybrid app. I am fetching and displaying the data using functions from json data provided by the web server. Below is a sample of the json data: [{"video_id":"1","video_youtube_title":" ...

Tips on converting HTML code into a data image URI

My question may seem unconventional, but here is what I am trying to accomplish. I want to create a design similar to the one found at the following link: I would like to embed text with an image and retrieve the data image URL using Ajax. I know how to g ...

Smarty is failing to generate Javascript on all files

I have a traditional PHP/Smarty Website setup. It consists of an index.php home base and a templates folder containing .tpl Files. The key templates include header.tpl, footer.tpl, index.tpl, and subpage.tpl. Both index.tpl and subpage.tpl include the hea ...

What is the best way to link together multiple tasks using JavaScript?

When faced with a series of asynchronous tasks such as task1, task2, task3, and so on, their relationships can be mapped out in a directed acyclic graph. This type of graph allows for the use of topological sorting to determine a possible execution route. ...

Using Selenium to assign properties to JavaScript Objects

I have a JavaScript Object that needs to be set using Selenium WebDriver. var examplePlayResponse = { "prizeIndex" : 1, "mode" : "NORMAL", "id" : "abc123", "version" : "1.0", "gameCode" : "xyz789", "randomSeed" ...