How can I identify and remove duplicate elements from an array of objects?

elements= [
  { "id": 0, "name": "name1", "age": 12, "city": "cityA" },
  { "id": 1, "name": "name2", "age": 7, "city": "cityC" },
  { "id": 2, "name": "name3", "age": 23, "city": "cityB" },
  { "id": 2, "name": "name1", "age": 12, "city": "cityA" }
];

I want to find elements with identical name and age. How can I achieve this?

I have attempted the following but it is returning all elements in the array:

data.some(d => {
for (const it of form) {
if (it.name == d.name && it.age == d.age) {
arr.push(it)....

Answer №1

Ensuring that you are not comparing the same item with matching properties is crucial:

data= [
  { "id": 0, "name": "name1", "age": 12, "city": "cityA" },
  { "id": 1, "name": "name2", "age": 7, "city": "cityC" },
  { "id": 2, "name": "name3", "age": 23, "city": "cityB" },
  { "id": 2, "name": "name1", "age": 12, "city": "cityA" }
];

const res = data.filter(item => data.some(i => i !== item && item.name === i.name && item.age === i.age))
console.log(res)

If excluding the first occurrence is desired, checking against previously processed elements is necessary:

data= [
  { "id": 0, "name": "name1", "age": 12, "city": "cityA" },
  { "id": 1, "name": "name2", "age": 7, "city": "cityC" },
  { "id": 2, "name": "name3", "age": 23, "city": "cityB" },
  { "id": 2, "name": "name1", "age": 12, "city": "cityA" }
];


const [result, _] = data.reduce(([duplicates, checked], el) => {
    checked.some(i => el.name === i.name && el.age === i.age) && duplicates.push(el)
    return [duplicates, [...checked, el]]
  }, [[], []]
)
console.log(result)

Sort-based strategies prove to be highly effective for such scenarios:

data= [
  { "id": 0, "name": "name1", "age": 12, "city": "cityA" },
  { "id": 1, "name": "name2", "age": 7, "city": "cityC" },
  { "id": 2, "name": "name3", "age": 23, "city": "cityB" },
  { "id": 2, "name": "name1", "age": 12, "city": "cityA" }
];
const sorted = data.sort( (e1, e2) => e1.name.localeCompare(e2.name) || e1.age - e2.age)
const result = sorted.filter( (el, i) => i > 0 && sorted[i-1].name === el.name && sorted[i-1].age === el.age)
console.log(result)

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 ngFor and click function in Ionic and Angular

Recently, I delved into the world of Ionic and started working on an app that features a unique 'dictionary' functionality. The app allows users to press a button to hear either an English or German translation of a Dutch word through an audio fi ...

Combining arrays using JavaScript

I'm struggling to enhance the following code - it looks a bit messy: Here is my data format: date d1 d2 d3 d4 d5 d6 110522 5 1 3 5 0 7 110523 9 2 4 6 5 9 110524 0 0 0 0 1 0 110525 0 0 3 0 4 0 ... I am importing data from a text file using d3.j ...

Pointers: The Surprising Results

I'm currently going through a book and I've encountered an example that's not clear to me. From what I understand, the array variable nums is actually a pointer to an array. In the next step, I create a variable called choice and assign it ...

How do I condense nested keys in TypeScript?

If I have two types defined in TypeScript: interface Foo { bar: string; } interface Baz { foo: Foo; } Is it possible to flatten the Baz type in TypeScript (e.g. type FlatBaz = Flatten<Baz>), so that the signature appears similar to this? inte ...

Combining and arranging numerous items in a precise location in three.js

I am currently working on a web application using three.js with Angular and facing some challenges when trying to set the precise positions of objects. The requirement is to load various objects and position them in specific locations. In order to load di ...

Tips for implementing <mat-progress-bar> in .ts file when making API service requests with Angular

I'm currently utilizing an API call to retrieve an image from a service, and I would like to display a progress bar while the image is being fetched. It seems that I need to incorporate the progress bar within the service as the image data is returned ...

Struggling to locate root directory post-Angular 13 upgrade in Jest

After updating my project to Angular 13, I realized that Jest required some adjustments as well. Now, any mention of 'src' cannot be resolved properly. For instance: Cannot find module 'src/app/app.component/app.component.test' from & ...

Exploring the Comparison of Arrays in AngularJS

I am currently working with two arrays: one for Usernames and another for userRoles. The structure of the arrays is as follows: Usernames = [ { "id": 1, "userName": "Jack", "description": "jack is a nice guy", "userRoleIds": [ 1 ...

What is the best way to selectively pass certain values to the args object?

Is there a way in TypeScript to pass only one argument into args and have other values be default without using "args = {}" or declaring defaults within the function to avoid issues with intellisense? function generateBrickPattern ( wallWidth: number, ...

The parameter cannot be assigned to type 'HTMLCanvasElement | null' due to conflicting arguments

I am encountering an issue with the following code, as it fails to compile: import React, {useEffect} from 'react' import {Card, Image} from 'semantic-ui-react' import * as chart from 'chart.js' export const PieChartCard = ...

Arranging two arrays: What's the best way to organize the numbers in my arrays

Given two arrays: int array1 [] = {1,2,3,4,5,6,7}; [The size of this array can increase significantly] int array2 [] = {1,2,3}; [Can contain a maximum of 30 elements] In this scenario, array1 is intended to be the parent loop and will have more elements ...

Setting a character array equal to a pointer to a character

Having some trouble writing a function that prefixes a string with its length. I'm running into an issue where I can't assign a char[] to a char *. Oddly enough, if I include some debugging code before the assignment, it seems to work. char *pre ...

What was the process for implementing the lexer and parser?

My journey into the depths of programming languages led me to explore how TypeScript is implemented, prompting me to venture into its Github repository. Within the language's source code under /src/compiler, I stumbled upon intriguing files like scan ...

How should a React Testing Library wrapper be properly typed in a TypeScript environment?

There's this code snippet from Kent C. Dodd's library that I find extremely helpful import * as React from 'react' import {render as rtlRender} from '@testing-library/react' import {ThemeProvider} from 'components/theme& ...

A windows application developed using either Javascript or Typescript

Can you provide some suggestions for developing Windows applications using Javascript, Typescript, and Node.js? ...

Can the MySQL results be stored in a single PHP array, similar to this format?

Is there a more efficient way to create an array like this array("123","456","789");? Here is the current code I am using: $Regids = mysql_query("SELECT regid FROM $tabel WHERE active = '1'"); while($row = mysql_fetch_array($Regids)) { $resu ...

Is a pointer to a complete object type required in the expression?

Attempting to modify an array of structures with the following code: typedef struct { char firstName[30]; char lastName[30]; char street[35]; char city[20]; char state[3]; int zip; char phone[15]; int accountId; } Customer ...

Encountering the ExpressionChangedAfterItHasBeenCheckedError error during Karma testing

Testing out some functionality in one of my components has led me to face an issue. I have set up an observable that is connected to the paramMap of the ActivatedRoute to retrieve a guid from the URL. This data is then processed using switchMap and assigne ...

Accessing base class properties in Typescript: A comprehensive guide

Although I have seen similar questions on this topic, my issue is unique. I have checked my class and am using it in the same way as others who have encountered similar problems. I extended class A into class B, but for some reason I cannot access A's ...

The async and await functions do not necessarily wait for one another

I am working with Typescript and have the following code: import sql = require("mssql"); const config: sql.config = {.... } const connect = async() => { return new Promise((resolve, reject) => { new sql.ConnectionPool(config).connect((e ...