Retrieve items with identical ids, all in a single representation

I have an array filled with objects. My goal is to identify and return the objects with unique IDs, avoiding any duplicates.

For example:

let arr1 = [
{id: 1, name: 'A'},
{id: 3, name: 'C'},
{id: 1, name: 'A'},
{id: 2, name: 'B'},
{id: 2, name: 'B'}
]

The desired result:

let newArr = [
{id: 1, name: 'A'},
{id: 2, name: 'B'}
]

The actual result:

let arr1 = [
{id: 1, name: 'A'},
{id: 3, name: 'C'},
{id: 2, name: 'B'}
]

I attempted the following solution:

arr1.reduce((destArray, obj) => {
    if (destArray.findIndex(i => i.id === obj.id) < 0) {
      return destArray.concat(obj);
    } else {
      return destArray;
    }
  }, [])

While this successfully filters objects by matching IDs, it also includes objects with somewhat unique IDs, which is not the desired outcome.

Answer №1

let filteredArr = arr1.filter((object, i, originalArr) => {
return originalArr.findIndex(item => item.id === object.id) === i && originalArr.lastIndexOf(item => item.id === object.id) !== i;
});

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

What is a regex with a touch of greed in its capture

I am considering the following options: ' !This is a string! ' '!This is a string !' '! This is a string !' ' ! This is a string! ' ' ! This is a string ' For each of these scenarios, I aim to find ...

Is there a way to logout when the select event occurs using the key?

I am trying to figure out how to log out the key value when the select event is triggered. Specifically, I want to access the key={localState.id} within the <select></select> element in my HTML. This key value is crucial for a conditional stat ...

Learn how to integrate ES6 features into your nodejs/expressjs application using either Gulp or Webpack

I am looking to incorporate ES6 features into my nodejs/expressjs application. Currently, I am using Gulp for JavaScript compilation and setting up live reload. What steps do I need to take in order to compile the es6 code to standard js within my exis ...

Attempting to program a bot to navigate in a random pattern across a two-dimensional xz plane using Threejs

My journey began with the code below, which initiates a block moving in a straight line: const bot_geometry = new THREE.BoxGeometry(1,1,1); const bot_material = new THREE.MeshBasicMaterial( {color: 0x7777ff, wireframe: false} ); const bot = new THREE.Me ...

How to Load an OBJMTL Object Using Three.js and Retrieve the Geometry Parameter of the Mesh

After loading an MTLOBJ successfully, I came across the issue of trying to access the Geometry attribute of the object in order to retrieve the vertices. It appears that it is loading an Object3D instead of a Mesh, making it difficult to find a solution. ...

Zend and qTip compatibility issues are causing problems

I am attempting to implement a help button in a Zend form using qTip 2. The button consists of a simple image, and my goal is to display a pop-in when the image is clicked. Here is my code: In Booostrap.php: protected function _initView() { ... ...

Are there any other options available in JavaScript to replace the .unload() function?

I have a click event attached to multiple buttons on my page, each loading a different .php file into the same div. The issue arises when the time to load increases after several clicks. $('#start').click(function() { $('#mainbody&apos ...

Encountering an Internal Server error with Mongoose in Node.js

My latest project is a web application designed for photo sharing. One particular route in the app is responsible for retrieving and displaying photos from all users in the following array. This is the route: router.get('/getphotos',function(r ...

Having trouble getting the timer function to execute upon page load in JavaScript

My goal is to have my basic timer function activate when the page loads. However, I'm encountering issues with it not working as intended. I suspect there may be an error in the if else loop, possibly here: setTimeout(function(tag, sec), 1000);. How c ...

HighCharts velocity gauge inquiry

I recently integrated a highcharts speedometer with PHP and MYSQL on my website. Everything seemed to be working smoothly until I added the JavaScript code for the speedometer, causing it not to display. There are no error messages, just a blank screen whe ...

Is there a way for me to revert back to my initial list after the 3rd click?

Front end development const [clientList, setClientList] = useState([]); //store all data from the database in a list //make an axios request to retrieve data from the database useEffect(() => { Axios.get("http://localhost:3001/clients&quo ...

JQuery is having trouble locating a variable in a different JavaScript file

Currently, I am utilizing the cakephp framework and have developed 2 distinct javascript files which I have stored in my webroot/js directory. The first javascript file includes modal dialog variables that define the settings for the dialog boxes. The seco ...

What are the implications of AngularJS's filter on performance?

I came across an interesting article on optimizing ng-repeat in AngularJS that discussed the following: An AngularJS filter in your HTML will run multiple times during every digest cycle, even if there have been no changes in the data or conditions. Thi ...

Maintaining the order of elements in Angular's insertion process

I am currently facing an issue with my HTML fragment that iterates over a key and value collection. Everything works perfectly when I insert values into an object and iterate through it using the HTML fragment. However, in order to maintain a specific key ...

What repercussions come from failing to implement an event handler for 'data' events in post requests?

If you take a look at the response provided by Casey Chu (posted on Nov30'10) in this particular question: How do you extract POST data in Node.js? You'll find that he is handling 'data' events to assemble the request body. The code sn ...

What is the process for adding or modifying attributes in child elements?

I have been experimenting with a simple script that adds the target="_blank" attribute to all the <a> elements. $(function(){ $('a').attr('target', '_blank'); }); While it is functioning perfectly, I am now interested ...

What is the best way to modify a node_module file consisting of only a few exported variables, which is heavily utilized in the entire module? (with demonstration)

I have integrated a node module with the file structure displayed below. Inside the file node_core_ctx.js, I found this code snippet: const EventEmitter = require('events'); let sessions = new Map(); let publishers = new Map(); let idlePlayers ...

What is the best way to create a list with images in a dropdown menu using HTML?

Thanks so much for your assistance! Below is the code snippet I am currently working on <li><a href="#Language">*LanguageHERE*</a></li> I am hoping to turn this into a dropdown menu that displays flags representing all available ...

The initial Ajax request returned an empty data string, but upon retrying, the correct data

Let's address the current situation Previously, I had a free domain that was unexpectedly closed by the web admins without any explanation. Everything functioned perfectly on that domain, but after opening a new one on a different site, I started enc ...

I keep encountering the issue where I receive the message "Unable to access property 'innerText' of an undefined element" when running the Array forEach function. This problem seems to be happening within the HTMLInputElement section of the code

I am facing an issue where the error occurs because "cardTxt" is not recognized as a string. I verified this using typeof syntax, but I'm unable to understand why it can't be a string. This code snippet includes the use of bootstrap for styling. ...