Investigate duplicate elements within nested arrays using the 3D array concept

I am dealing with an array that contains 3 subarrays.

Arr = [[arr1],[arr2],[arr3]]

My task is to identify and store the duplicate values found in these subarrays ([arr1],[arr2],[arr3]) into a separate array.

Arr2 = [ Duplicate values of arr 1,2,,3 ]

What would be the most effective way to accomplish this using JavaScript?

Answer №1

This code snippet offers a unique approach to solving the given problem.

const data = [
[1,1,2,1,3], 
[2,1,4,4,5],
[3,1,4,5,1]
];

// Flattening the two-dimensional array into a single dimension
const transformedArray = data.flat();

const uniqueValuesArray = [];
const duplicateCounts = [];

// Create an array with only unique values
transformedArray.forEach(item => {
    if(!uniqueValuesArray.includes(item)) {
        uniqueValuesArray.push(item);
    }
});

// Count the occurrences of each unique element
uniqueValuesArray.forEach(uItem => {
    const count = transformedArray.filter(tItem => tItem === uItem).length;
    duplicateCounts.push({
        element: uItem,
        count: count
    });
});

// Testing the output
console.log(transformedArray);
console.log(duplicateCounts);

Answer №2

Initially, my plan was to combine the arrays into a single large array, but it seems like you are interested in finding duplicates that exist in all arrays:

var arr1 = [1, 2, 3, 4]
var arr2 = [1, 2, 4, 8]
var arr3 = [2, 4, 6, 8]
var duplicates = [];
arr1.forEach(function(item) {
  // You can switch && to || if needed
  if ((arr2.indexOf(item) > -1) && (arr3.indexOf(item) > -1)) {
    duplicates.push(item)
  }
})


console.log("" + duplicates)

Answer №3

Here is a straightforward solution to your query:

const arrayOne = [3, 7, 9, 11];
const arrayTwo = [1, 4, 5, 7];
const arrayThree = [2, 7, 13];

const commonElements = arrayOne.filter((num) => arrayTwo.includes(num) && arrayThree.includes(num));

console.log(commonElements);

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

.toggleClass malfunctioning inexplicably

I've been struggling to make a div box expand when clicked and revert to its original size when clicked again. It seems like a simple task, but no matter what I try, I can't seem to get it right. I'm not sure where I'm going wrong, as t ...

How can I identify the moment when an AngularJS route controller is no longer in scope?

Currently, I have a controller set up to poll the server at regular intervals using $timeout. The issue arises when the route changes - I need to stop the polling and then restart it once the original route is accessed again. If anyone has any suggestions ...

What is the best way to combine a specific number of arrays in JavaScript?

Currently, I am working on a program that is designed to read lines from multiple text files and store those lines in separate arrays for each file. Eventually, the goal is to combine all of these arrays and randomly select an item from the merged array. H ...

A guide on setting the array value on the user interface based on a key within the SectionList

My code is currently retrieving an array value and populating these values based on the key in a SectionList. The keys are displaying properly in the UI, but I am encountering some issues in my render item function, particularly in the second section. Esse ...

What are some ways to ensure that the promise from postgres is fulfilled before moving forward with my code execution?

I am currently developing a Node-js application that requires retrieving information from the database before making another database call. However, I am facing an issue where the first check is not always resolved before proceeding to the next step. I hav ...

Ways to prevent recurring variables in Twitter bootstrap dialogues

I need assistance with deleting multiple links using ajax: <a id="id-1">link1</a> <a id="id-2">link2</a> <a id="id-3">link2</a> <a id="id-4">link2</a> ... This is the simplified version of my code: $(docum ...

Passing JSON data with special characters like the @ symbol to props in React can be achieved

Using axios in React, I am fetching JSON data from a database. I have successfully retrieved the JSON data and stored it in state to pass as props to child components within my application. However, the issue arises when some of the objects in the JSON s ...

Can the variable name within a function be retrieved?

How can I retrieve the variable name (user_name1 or user_name2) from a sample function (GetUserName()) within itself? This variable name is required to create an object with the same name on the server side for data synchronization purposes. function GetU ...

Enhancing CKEditor: Inserting new elements upon each dialog opening

I am facing a challenge where I need to dynamically add varying numbers of elements to a dialog window each time it is opened. Below is the code I am working with: CKEDITOR.on( 'dialogDefinition', function(ev) { var dialogName = ev.data.name ...

Discovering the process of retrieving API data upon a button click within Next.js using server-side rendering

Hi there, I'm fairly new to working with next.js and would greatly appreciate some assistance. I am trying to figure out how to fetch data from an API upon clicking a button in next.js on the server side. I understand that using onClick directly is ...

"Engage with an Angular directive using a button positioned in any location on the

There is a directive implemented on my webpage with an assigned id attribute, regardless of its functionality. Now, I need a second directive that essentially triggers the first one. Here is an example of what I aim to achieve: <body> <!-- v ...

inability to conceal a two-dimensional marker array within Google Maps API v3

I need some help with my marker that refuses to hide Even after using setMap, my marker is still visible on the map Here is the error message from the console Please assist! Thank you in advance markers[i][j].setMap(null); markers.setMap(null); va ...

Issue with Android date input field not resetting the value

When testing in Android Tablet (version 4.1.2), I encountered a strange issue with an input date field that looks like this: <input type="date" value="2013-06-10"/>. Upon clicking on the field and trying to set a new date, instead of replacing the o ...

Remove an item from Firebase using React with ES6 syntax

[HELP NEEDED]Seeking solution below Encountering an issue with deleting an object from the Firebase database. I have experience with this, but for some reason it's not functioning as expected: Action: export const firebase_db = firebase.database(). ...

Creating dynamic qtip2 tooltips is an effective way to enhance user interaction on

I am facing an issue where all tooltips work perfectly fine when the page loads, but stop working after data refreshes through ajax. How can I resolve this problem? $(document).ready(function() { // MAKE SURE YOUR SELECTOR MATCHES SOMETHING IN YOUR HT ...

"Retrieve an image source using a jQuery Ajax call and swap it on

I am working on a webpage that includes an <img src="..." /> tag with a default src set. My goal is to use jQuery to make an ajax request to fetch another image, and only once this new image has fully loaded, update the src attribute of the <img ...

Is there a way to retrieve the request URL within the validate function of the http strategy?

Is it possible to access the context object present in guards within the validate method of my bearer strategy, by passing it as an argument along with the token? bearer-auth.guard.ts: @Injectable() export class BearerAuthGuard extends AuthGuard('be ...

The AutoComplete feature in Formik Field from Material UI component is not showing the InitialValues

Having an issue with displaying the initialValues in the AutoComplete component from the Material UI library when used in a Formik Field. Even though values are passed as initial, they do not render in the component, although if the form is submitted, they ...

Tips for successfully parsing JSON data during an Ajax call

After making an Ajax call, the response.responseText I receive looks like this: . "[ columns :[ { "id":"name", "header":"User name" }, { "id":"birth", "header":"Date of birth" } ], ...

What is the best way to compare the previous and next values in React?

When working with the code snippet below to send a list of values to another component - React.createElement("ul", null, this.state.stock.map(function (value){ return (React.createElement(Price, { price: value })) }) ) the values are then sent t ...