How can we generate an array of duplicated values from an array that already contains duplicates in JavaScript?

Given an array of objects like

["a","b","a","c","d","b"]
, how can I efficiently retrieve an array of the duplicate elements, such as ["a","b"]? Is there a method similar to using set ([...new Set(myArray)];) for this purpose?

Answer №1

If you want to efficiently filter an array for duplicates, consider using a Set and checking for existing values.

const
    elements = ["x", "y", "z", "x", "y", "w"],
    uniqueElements = elements.filter((set => value => set.has(value) || !set.add(value))(new Set));

console.log(uniqueElements);

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

When trying to implement appDir and withPWA in next.config.js, an error has been encountered

My next.config.js is set up with next-pwa and an experimental app feature included. const withPWA = require('next-pwa'); module.exports = withPWA({ pwa: { dest: 'public', disable: process.env.NODE_ENV === 'development&ap ...

Leveraging vue.js props in the mounted function

In my current Vue.js project, I have encountered an issue while using props to pass a value from one component to another. The value received from the props is stored in a variable called "this.Id". I am able to display this value using an alert within the ...

Personalize the loading bar using JavaScript

Currently, I am utilizing a basic progress bar from Bootstrap. However, I have the desire to design a custom progress bar similar to this: Unfortunately, I am uncertain about how to create such a unique progress bar. Perhaps there is an existing JavaScri ...

How come I can't capture discord.js promise rejections within event callbacks?

As I delve into creating a discord bot, I encountered an interesting problem. To simplify things, here is a snippet that encapsulates the issue at hand: const Discord = require('discord.js'); const client = new Discord.Client(); client.on(&apo ...

What is the method for adding a new value to an array stored in a data attribute using square brackets around a text input?

I am dealing with an element that contains an array specified in the following code snippet: <div class="home_team" data-home='["10","20","30"]'></div> Whenever I input a value in the text fi ...

The functionality of the Eslint object-property-newline feature is not functioning as expected

Within my configuration file .eslintrc, I have set "object-property-newline": ["error", { "allowAllPropertiesOnSameLine": true }], and "max-len": "off". However, objects like const something = {a: 5, ffsdfasdasdsddddd: 'asdasdasdddddddddddssssssddddd ...

I'm thinking about transitioning my current React app to Next.js. Do you think it's a good move?

We have recently transitioned our project from react-redux with firebase authentication and solr DB to next.js. Below is the updated folder structure of our app: --src --actions --assets --components --controllers --firebase --redu ...

How to use a Mongodb query to identify the data type of elements within a nested array or object in a field

Within my mongodb data model, I have array fields that contain embedded objects or arrays. Due to adjustments in my application logic, there are inconsistencies within these fields. Initially, the model appeared as follows: Original Configuration of Resul ...

Moving back and forth within a range

One simple yet commonly encountered task involves looping through a range forwards and backwards: var currentIndex = 0; var range = ['a', 'b', 'c', 'd', 'e', 'f']; function getNextItem(directi ...

Adjust the color of the upcoming line I am sketching without ending the path

I am working on a paint program and encountered an issue. My goal is to create buttons of various colors that can change the color of the next stroke drawn by the user. While searching for a solution, I came across a similar question (HTML5 Canvas change ...

Automatically install the development version of NW.js when running 'npm i'

Is it possible to automate the installation of the developer version of NWJS from package.json, similar to when I run npm install? For example, if I type npm i nw --nwjs_build_type=sdk I attempted to set an environment variable in my package.json like th ...

JavaScript issue with confirm/redirect feature not functioning as expected

A demonstration of JavaScript is utilized for deleting an employee in this scenario... <script type="text/javascript"> function deleteEmployee(employee) { var confirmation = confirm('Are you sure?'); if(confirmation) { ...

Differences in how line breaks are handled in script output have been observed when comparing Atom and Notepad

Currently, I am utilizing a small script that generates a .txt file and inputs some data into it. Strangely, when I open the .txt file in Atom, the content appears on separate lines as I intended. However, when I access the same file in notepad, all the co ...

Function in React not being successfully passed down between functional components

I have been accustomed to using class components and now I am transitioning into functional components in order to become more proficient with hooks. However, I have encountered an issue where I am struggling to pass a function from one functional compone ...

Unable to display images in the ngImgCrop upload preview modal screen

Currently, I am utilizing ngImgCrop to enable an upload preview and square crop feature for profile pictures. Unfortunately, I am experiencing issues where neither the image preview nor the cropping functionality are being displayed. 'use strict ...

The specified function for handling NetworkError is currently unavailable

I'm trying to implement a retry mechanism for URL calls in case of network failure using the 'cockatiel' library. Below is the code snippet I have written: import { retry, handleType, ExponentialBackoff} from 'cockatiel'; const ...

Tips on altering the location path when redirecting to a different page using window.location?

Is it a silly question to ask? I tried looking for the answer on Google but couldn't find it. I'm currently working on a website where users can upload photos or videos, using HTML, CSS, and JavaScript. On the homepage, when a user clicks on a ...

Error: Node.js/Express unable to connect to static assets

I recently deployed my Express application to a production server and encountered an issue with serving static assets. All of my assets are located in the /public directory, and I am using the following code to call the static middleware: // config.root ...

Angular - Showcasing Nested Objects in JSON

I am experimenting with using angular ngFor to iterate through this data: Link: Although I can successfully retrieve the data by subscribing to it, I encounter an issue when trying to display attributes that contain objects. The output shows as [object O ...

Simplify your bootstrap Input field code by utilizing components or a similar method in Vue.js

Using a single file component with a pug template, I am faced with multiple input fields that have the same formatting. Here is an example: .input-group.input-group-sm .input-group-addon Purchase Price input.form-control(v-model='purchase_ ...