How can we use Javascript to determine if there are any duplicated IDs within an array containing multiple arrays?

Currently, I'm facing a challenge in identifying duplicated values within an array. Let's consider the scenario where we have an array of arrays:

array = [
  { id: 123, name: 'Emily', address: 'UK' },
  { id: 123, name: 'Ross', address: 'USA' },
  { id: 157, name: 'Joey', address: 'Italy' },
];

In this example, there are two arrays with the same ID id=123. It is crucial to detect these duplicates to ensure clean data.

Specifically, my focus lies on checking for duplication based on IDs and Names simultaneously. Although I attempted a logical solution, it failed to provide accurate results by returning more rows than necessary:

ngOnInit() {
    this.array.forEach((row) => {
      this.array.find(element => {
        if (element['id'] === row['id']) {
          console.log(row)
        }
      })
    })
  }

The current output appears as follows:

123 Emily

123 Emily

123 Ross

123 Ross

157 Joey

My desired output should be:

123 Emily

123 Ross

If you want to explore further, here is a link to the code snippet on StackBlitz.

Answer №1

If you're looking for a distinct-like behavior, try using filter and map in the following way:

function getDistinctValues(myArray, property) {
    return myArray.filter((item, index, array) => {
        return array.map(mappedItem => mappedItem[property]).indexOf(item[property]) === index;
    });
}

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: Array index exceeds limit`

I'm currently learning how to use processing and working on a project that involves filling a 600px by 600px canvas with 50px rectangles of random colors from my orange[] palette. The random arrangement of blocks needs to be implemented within the dra ...

Ways to handle errors when using navigator.clipboard.writeText

document.queryCommandSupported('copy') may not be available on all browsers. I experimented with the code below, which successfully copies the link on Firefox but fails on Opera. It displays an alert indicating that the code has been copied, yet ...

The TypeAhead feature fails to display any search results for the entered query

Feeling really desperate right now! I'm facing a frustrating issue with Bootstrap Typeahead. Here is the HTML Markup: <div class="form-group"> <label for="">Recipients</label> <input id="recipients" name="recipients" ...

Issue with submitting forms through Mozilla's browser

I am currently in the process of developing a dynamic form with the code snippet below: function createForm() { var f = document.createElement("form"); f.setAttribute('method',"post"); f.setAttribute('action',"./Upload"); ...

Quickly switch between pages as they load

In Chrome, I'm experiencing a white flash between page loads that is causing transitions to appear choppy. I've taken various steps to optimize the site, such as using image sprites, reducing image sizes, minifying CSS, ensuring correct CSS loadi ...

What is the most efficient method for managing components with dynamic templates and their corresponding data in Vue.js?

I have a question and requirement that I would like to discuss. It involves dynamically rendering templates and data using components. The scenario is as follows: The root Vue instance fetches data from the backend, and let's say the following data i ...

Using Angular's $http service to send a file to a web API endpoint from a post function

I'm facing an issue with uploading a javascript file or transmitting a javascript file to a post function. On the client side, I am using angularjs $http service to send the data as follows: $http({ method: "POST", ...

beforeunload event confirmation prompt

I am currently working with Laravel and Vue.js to create a multi-step wizard. Within this wizard, I have implemented the onbeforeunload event to prevent any unwanted actions by displaying a confirmation message. However, I am encountering an issue where th ...

Is it necessary to use the "new" keyword when utilizing JS closure to create objects?

My response to a question about closures on SO included the following code sample: function Constructor() { var privateProperty = 'private'; var privateMethod = function(){ alert('called from public method'); }; ...

Retrieving the request body in AWS Lambda

Within my AWS Lambda function running on NodeJs 8.0 and receiving requests from API Gateway, the code is structured as follows: const mysql = require('mysql'); exports.handler = (event, context, callback) => { console.log("event.body = " ...

Troubleshooting the clonewithrows array problem in react-native

I am currently facing an issue while trying to populate a Listview in my react-native application using data from Firebase. The error message I am receiving is as follows: "Objects are not valid as a React child (found object with keys {title}). If you me ...

Is there a more efficient method for generating dynamic variable names from an array aside from using eval or document?

I need help figuring out how to create an array in JavaScript or TypeScript that contains a list of environment names. I want to iterate over this array and use the values as variable names within a closure. My initial attempt looks like this (even though ...

Integrating a Google map into an Ionic Side-Menu application

I am trying to incorporate a Google map into my Ionic app. I followed the code provided in this https://developers.google.com/maps/documentation/javascript/adding-a-google-map and it worked fine in Angular, but not in my side-menu Ionic project. The specif ...

Steps to update the border color to red when a button is clicked

I have an interesting question regarding validation and forms. I decided to use my own class, but I noticed that when the button is clicked, the border color does not display anymore. I tried testing with CSS for invalid entries, and it worked. Now, I wan ...

Working efficiently with query selectors in React using useRef

I have created a typewriting effect function and now I am trying to display the code associated with this effect within a specific div element (typingRef). Currently, I am using typingRef.current = letter, but I am wondering if this is equivalent to docu ...

I am encountering difficulty in printing multiple documents from FireStore

I am facing an issue where I can successfully retrieve and print all documents from a Firestore collection one by one using console.log(). However, when attempting to display these documents on the screen, only the most recent document is showing up. Here ...

What is the best approach to replace null values with undefined specifically in object properties that cannot be assigned to?

type GraphQLInput = { email: string; age?: null | number | undefined; height?: null | number | undefined; } type PrismaPerson = { email: string; age: number | undefined; height: null | number; } let input: GraphQLInput = { email: "< ...

Errors are being encountered when retrieving Shadow Shader Chunks

As I work on combining a basic toon shaded ShaderMaterial with threejs' built-in shadow system, I encountered some errors. It seems that when I set the Mesh's recieveShadow property to true, I run into issues. The errors I am facing are: Vertex ...

Discover patterns within a 2D array by using Python to analyze and count occurrences

Presented below is a dataset: data = np.array([[1, 0,-1, 0, 0, 1, 0,-1, 0, 0, 1], [1, 1, 0, 0,-1, 0, 1, 0, 0,-1, 0], [1, 0, 0, 1, 0, 0,-1, 0, 1, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0]]) The goal is to ...

Is there JSON data available to determine the overall attendance rate in percentage?

I have a set of attendance data for a specific student. Each subject is marked with a 1 if the student was present, and a 0 if absent on a particular date. I need assistance in calculating the total attendance based on this information... { " ...