Determine the shared elements within a single array by utilizing Javascript

I have the following array of mergeUniqueItems:

var mergeUniqueItems = ["-JsDEcxz_ZSGFLKwd1QM", 
"-JsJ2NXGDYKI6QRsuXVK", 
"-JsJ2RK-kOG2eGcG04xF", 
"-JsJ2RK-kOG2eGcG04xF", 
"-JsJ2YLPiP6751zh8geS"]

After using this code snippet, I encountered an issue:

    var duplicateArray = [];
    for (var i = 0; i < mergeUniqueItems.length; i ++){
        for (var j = 1; j < mergeUniqueItems.length; j ++){
            if (mergeUniqueItems[i] == mergeUniqueItems[j]){
                duplicateArray.push(mergeUniqueItems[i]);
            }
        }
    }

    console.log(duplicateArray);

The resulting duplicateArray contains the following items:

["-JsJ2NXGDYKI6QRsuXVK", 
"-JsJ2RK-kOG2eGcG04xF", 
"-JsJ2RK-kOG2eGcG04xF", 
"-JsJ2RK-kOG2eGcG04xF", 
"-JsJ2RK-kOG2eGcG04xF", 
"-JsJ2YLPiP6751zh8geS"]

However, my expectation is to have only one array entry for each duplicated item like below:

 ["-JsJ2RK-kOG2eGcG04xF"]

If there are multiple duplicate values, the array should display them as follows:

["-JsJ2RK-kOG2eGcG04xF", "another_duplicate_1", "another_duplicate_2", ...]

I am unable to determine what's causing this issue with my code. Your assistance would be greatly appreciated.

Thank you

Answer №1

Make a small change by initializing j as i+1 instead of just 1, and ensure that you are not adding duplicate values.

for (var i = 0; i < mergeUniqueItems.length; i ++){
    for (var j = i + 1; j < mergeUniqueItems.length; j ++){
        if (mergeUniqueItems[i] == mergeUniqueItems[j]){
            if (duplicateArray.indexOf(mergeUniqueItems[i]) < 0)
                duplicateArray.push(mergeUniqueItems[i]);
            break;
        }

Answer №2

Here's an alternative approach to Pointy's solution.

const uniqueValues = mergeUniqueItems.filter((item, index, originalArray) => {
    return originalArray.indexOf(item, index + 1) === -1;
});

console.log(uniqueValues);

This method is more concise and avoids explicit loops.

Keep in mind that this method keeps the last duplicate item. To retain the first one instead, use .indexOf(item, index - 1).


If you only want a single instance of each duplicate, you can do it like this:

const duplicates = mergeUniqueItems.filter((item, index, originalArray) => {
    const nextIndex = originalArray.indexOf(item, index + 1);
    return nextIndex !== -1 && originalArray.lastIndexOf(item) == nextIndex;
});

Alternatively, try this method:

const duplicates = mergeUniqueItems.filter((item, index, originalArray) => {
    const nextIndex = originalArray.indexOf(item, index + 1);
    return nextIndex !== -1 && originalArray.indexOf(item, nextIndex + 1) === -1;
});

Another option is to chain two .filter() methods:

const duplicates = mergeUniqueItems.filter((item, index, originalArray) => {
    return originalArray.indexOf(item, index + 1) !== -1;
}).filter((item, index, originalArray) => {
    return originalArray.indexOf(item, 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

Error: Unable to assign value to '18dit075' property as it is not defined in Node.js

var id = req.query.id; var username = req.query.name; var password = req.query.password; console.log(req.query); var data = { people:{ } } data.people[id] = { username: username, password: password, ...

I am attempting to insert a collection of objects into my MongoDB database using Node.js

My goal is to store an array of objects into my mongodb database using the obj dummy data. However, when I run the code, it only saves an empty array instead of the objects. Here is the breakdown of my code: Schema const mongoose = require('mongoose& ...

Eliminate any duplicate items from the array containing objects

I've been struggling with this issue for a week now, hopefully someone here can help me out... The application I'm working on was created using Laravel with Vue for the frontend. Essentially, I have an array of objects that need to be sent to t ...

Creating a stunning art exhibition using React Native

Currently, I am in the process of creating a gallery component that utilizes both the scrollview and image APIs. I'm curious about how the scrollview manages its child components when it scrolls down. Does it unmount the parts that are not currently ...

Dynamic content with Socket.io in Node.js

I am attempting to create a scenario where nodejs triggers an event in an irc chat that causes a html page (Running on *:3000) to execute some JavaScript. However, I am facing an issue where the showDiv(); function is not being executed as expected. Curre ...

What is the best way to keep track of a checkbox's value after unchecking it and then returning to the same slide?

Issue: By default, the checkbox is always set to true in the backend code. Even if I uncheck it using JavaScript, the value remains as true when switching between slides. Desired Outcome: If I uncheck the checkbox, the updated value should be saved so tha ...

Utilizing AngularJS: Establishing a Universal Parent State in UI-Router for Modals and Shared Components

In my code using UI-Router and Bootstrap-ui modal, I have defined the state as shown below. reference var state = { name: 'modala', parent: 'home', onEnter: function($modal, $state) { modalInstance = $modal.open({ ...

JavaScript Conversion of Characters to ASCII Values

After converting a string input into a split array, I now need to convert that split array into ASCII for evaluation. Can someone provide guidance on how to do this? ...

` `issues with fmt:massage tag` `

When I try to update my page elements using ajax, I encountered a problem: the fmt:message tag doesn't work when I set it in javascript. In the JSP page everything works fine: <div id="div"> <fmt:message key="search_select_country"/> & ...

How to efficiently eliminate duplicates from an array list using React framework

Keeping the array name constant while duplicating and repeating this process only clutters the list. Appreciate your help. setListItems(contents.data); console.log(contents.data); ...

Ensure each list item is directly aligned when swiping on a mobile device

Looking to make a simple horizontal list swipeable on mobile devices with tabs that snap from tab to tab, activating the content for the active tab immediately. The desired effect is to swipe directly from one tab to the next without having to click separ ...

How can you store a Json Object with nested arrays, including other Json objects, in a single table in an SQL database?

I develop applications using the Spring framework. Below is a snippet of JSON data (an array of JSON objects) that I am working with: [{"id" : 643419352, "status" : "removed_by_user", "url" : "https://www.o ...

Updating HTML5 localStorage value upon a click

Currently, I have implemented a countdown timer using the provided code snippet. To prevent the count from resetting upon page refresh or reload, I am utilizing local storage. However, if there is an alternative solution to achieve this functionality, I wo ...

Is there a way to retrieve the HTML code of a DOM element created through JavaScript?

I am currently using java script to generate an svg object within my html document. The code looks something like this: mySvg = document.createElementNS("http://www.w3.org/2000/svg", "svg"); myPath = document.createElementNS("http://www.w3.org/2000/svg", ...

Find and Scroll Dropdown Menu with Bootstrap Framework

Access the jsfiddle for more information. Have a look at these questions: In my dropdown menu, I have included a search box and multiple sub-menus. However, the search box only filters the first dropdown menu and does not work with the sub-menus. How ca ...

Iterating through a JSON object to verify the presence of a specific value

I have a JSON Object and I am looking for a way in Angular 6 to search for the value "Tennis" in the key "name". Can you provide guidance on how to achieve this? { "id":2, "name":"Sports", "url":"/sports" "children":[ { "id":1, ...

Angular Starter Kit

When starting with Angular.js, there are various boilerplate kits available such as angular-seed, some incorporating requirejs and more. However, many of the options I've come across seem to be outdated. As a newcomer to Angular, I'm wondering if ...

After refreshing the page, the local storage does not appear

I've been struggling to get it working for hours with no luck. After submitting the form, I create local storage values for name, surname, and email so that they can be automatically filled in the form next time without requiring the user to retype th ...

Encountering issues with rendering in React JS when utilizing state variables

I've been attempting to display content using the render method in React JS, but for some reason, the onClick code isn't executing. I'm currently enrolled in a course on Udemy that covers this topic. import React, { Component } from 'r ...

Different methods for organizing an array of strings based on eslint/prettier

I possess an assortment of keys that I desire to sort in alphabetical order whenever I execute eslint --fix/prettier. My inference is that such a feature does not exist by default due to its potential impact on the code's behavior. Therefore, my quer ...