Removing all repetitions from an array in JavaScript

My collection of objects includes the following inputs:

var jsonArray1 = [{id:'1',name:'John'},{id:'2',name:'Smith'},{id:'3',name:'Adam'},{id:'1',name:'John'}]

There is a duplicate id '1' that I would like to eliminate from my output. The desired result should be:

[{id:'2',name:'Smith'},{id:'3',name:'Adam'}]

I am seeking guidance on how to remove all duplicate records from the array. Can you provide me with direction on this?

Answer №1

To create a Map using an array, designate the key of the Map as your desired id. Duplicate entries will not be preserved (only the last occurrence will). Then, extract the values from the Map.

If you want to remove all instances of duplicates (as specified by the original poster):

const input = [{id:'1',name:'John'},
               {id:'2',name:'Smith'},
               {id:'3',name:'Adam'},
               {id:'1',name:'John'}]

const result = input.filter((x, i, arr) => 
                          arr.filter(e => e.id === x.id).length === 1)
console.log(result)

To retain one occurrence of duplicates:

const input = [{id:'1',name:'John'},
               {id:'2',name:'Smith'},
               {id:'3',name:'Adam'},
               {id:'1',name:'John'}]

const uniqueEntries = [...new Map(input.map(item => [item.id, item])).values()]
console.log(uniqueEntries)

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

A Step-by-Step Guide to Setting Up a Scoreboard for Your Rock Paper Scissors Game

I'm new to JavaScript and I want to create a rock, paper, scissors game from scratch. My Game Plan: Once the user clicks on an option (rock, paper, scissors), the game will display their score and the computer's score along with the result of t ...

The React Testing Library encountered an error: TypeError - actImplementation function not found

Encountering a TypeError: actImplementation is not a function error while testing out this component import React from 'react'; import { StyledHeaderContainer, StyledTitle } from './styled'; export const Header = () => { return ( ...

Even though setState is supposed to update the state and trigger a render, it's not showing up in the view for some

My React app consists of a simple word/definition feature. There is an edit box that appears for users to change the definition when they click on "edit". Even though I call getGlossary() to update the new definition in the state, I can see the changes in ...

Rotate the circular border in a clockwise direction when clicked

I have successfully designed a heart icon using SVG that can be filled with color upon clicking. Now, I am looking to add an outer circle animation that rotates clockwise around the heart as it is being created. Currently, the circle only spins in the code ...

Inquiry regarding JSON manipulation and serialization techniques

I am facing an issue with passing a List of Skills along with a strongly typed view containing an object Person in my viewmodel. Working with the object Person using Html Helpers like @Html.TextBoxFor(m => m.Person.FirstName) is straightforward and I ca ...

Conflicting behavior between jQuery focus and blur functions and retrieving the 'variable' parameter via the $_GET method

There is a simple focus/blur functionality here. The default value shown in the 'Name of Venue' input field changes when the user clicks on it (focus) and then clicks away(blur). If there is no text entered, the default value reappears. Input fi ...

Creating a Query String in a web URL address using the state go method in Angular State Router

On my product list page, there is a list of products. When I click on a particular product, a function is called that uses state.go. Issue with dynamic functionality: $state.go('home.product.detail', { 'productID': "redminote4", &apo ...

Float and tap

Can someone assist me with my code? I have 4 identical divs like this one, and when I hover over a link, all the elements receive the same code. <div class="Person-team"> <div class="profile-pic-d"> <a cl ...

What is causing the error to appear in the Android web-view when using vue.js?

During the development of my web app using Vue.js, I encountered a strange issue where everything was functioning correctly in desktop browsers but not on mobile devices. To troubleshoot this problem, I decided to install an Android emulator and use remote ...

How can I convert the date format from ngbDatepicker to a string in the onSubmit() function of a form

I'm facing an issue with converting the date format from ngbDatepicker to a string before sending the data to my backend API. The API only accepts dates in string format, so I attempted to convert it using submittedData.MaturityDate.toString(); and su ...

Tips on customizing regex to selectively identify specific strings without capturing unrelated ones

Currently, I am working with this regex: /(?<=^|\/)(?:(?!\/)(?!.*\/))(.*?)[:-]v([\d.-]+)(?=\.|$)/ The goal is to extract the captured group from the following strings: rhmtc/openshift-velero-plugin-rhel8:v1.7.9-4 oc-mirror-plug ...

What is the best way to integrate a Ruby object into JavaScript?

I'm attempting to integrate Ruby into the JS.erb file, where I need access to the @user object and its relationships. Instead of converting to a JSON object, I prefer the ERB to precompile on the server-side. My goal is to iterate in the JS file rat ...

Querying an array using the Contentful API

Recently, I've been experimenting with the Contentful API (content delivery npm module) and have encountered a challenge that I'm not sure how to overcome. In my Contentful setup, I have a content type called tag which consists of one field, als ...

Node.js socket.io emit function not functioning properly

In my current configuration, I have the following setup: app.set('port', process.env.PORT || 3000); var httpserver = http.createServer(app).listen(app.get('port'), function(){ console.log('Express server listening on port ' ...

arrange a collection within an array containing keys as strings

I am facing an issue with sorting an array of objects. I need to sort the 'list' by 'score' in descending order. var list =[{ '440684023463804938': { score: 6, bonuscount: 2 }, '533932209300832266': { score: 20, b ...

Executing a for loop just once in JavaScript

var door1 = {open: false,car: false,choose: false}; var door2 = {open: false,car: false,choose: false}; var door3 = {open: false,car: false,choose: false}; var carName = 0; var objectName = 0; var goatName = 0; var min = 1; var max = 4; var random = Math. ...

The getJSON function yields a null value

When using the jQuery getJSON function, I am getting a null response even though everything seems to be written correctly: $.getJSON("/site/ajax/autocomplete/key", function(data) { alert(data); //null alert(data.term); //null }); I am working wit ...

Get the value of an HTML element

Is there a way to retrieve the value of an HTML element using PHP or JavaScript, especially when the value is dynamically loaded from another source? I have tried using jQuery with the DOM ready event, but often encounter the issue where the element's ...

Extract the JSESSIONID and generate a new Cookie using AngularJS

Currently, I am utilizing a Web RESTful API from my client within AngularJS. app.controller('LoginController', [ '$http', '$cookies', function($http, $cookies) { this.credentials = {}; this.http = $ ...

End the div element upon completion of the Vimeo video

I am in need of a website that includes an intro video displayed as a full-width div over the background content. To achieve this, I created a Div containing an iframe video from Vimeo along with a button to skip the intro (which closes the div upon clicki ...