Remove duplicate objects from an array by a specified property using AngularJS

I am managing an array called $scope.notys in my controller and using ng-repeat:

<li ng-repeat="x in notys" class="item js-item">
...

To add data to the array from my controller, I use this method:

$scope.notys.push(data);

Each piece of data includes a unique id property called data.id

The question I have is how can I update or replace an object where the id property matches with the last data.id received from an ajax call?

So basically, I need to follow these steps:

  1. Retrieve data from the ajax call

  2. With the new data.id, I need to check if there is already an object in $scope.notys with the same id

  3. If an object with that id already exists, then replace it with the latest data. If not, simply add the new data by using push

Answer №1

One approach to transform your array into key-value pairs (id-index) involves utilizing the array.reduce method. By establishing the id as a key, you can easily determine the corresponding index. This allows you to use array.splice with that index to replace the existing element with a new one.

var data = [{id:1, value:'apple'},{id:2, value:'banana'}]
var idIndexPair = data.reduce(function(result, entry){
  result[entry.id] = entry.value;
  return result;
}, {});

var newItem = {id:1, value: 'cherry'};
var positionOfExisting = idIndexPair[newItem.id];

if(positionOfExisting !== undefined) data.splice(positionOfExisting, 1, newItem);

document.write(JSON.stringify(data));

Answer №2

Here is a straightforward approach I discovered:

Using Angular's forEach method, I iterate through the $scope.notys array to find and remove any existing element with the same id as the data being passed in. Once removed, I then add the new data element to the array.

This process ensures that duplicate elements are avoided by first removing any potential duplicates before adding the new element.

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

Sort through a list of objects using the criteria from a separate array

Looking to apply a filter on an array of objects: const myArray = [{ id: 4, filters: ["Norway", "Sweden"] }, { id: 2, filters :["Norway", "Sweden"] }, { id: 3, filters:["Denmark", "Sweden&q ...

Exploring for duplicated elements in a two-dimensional array of integers

I am working with a 2-dimensional integer array that contains 3 numbers in each index. For instance: exampleArray = new int[][] { {0, 0, 0}, {0, 1, 0}, {0, 0, 1}, {1, 0, 1}, }; My goal is to determine if the first two numbers in each in ...

JavaScript and Node.JS tutorial: Pause execution until a folder is copied, then proceed to modify its files using asynchronous functions and await

I am currently developing a node.js application that involves copying a directory and then making modifications to the files within it. However, I have encountered an issue where my code attempts to edit the files before the copying process is fully comple ...

Discover the position of a dynamically added element

Is there a way to identify the specific dynamically added checkbox that was clicked, whether by index or name? I came across a similar question with a solution in this JSFiddle: JSFiddle Instead of just displaying "clicked", I would like it to show someth ...

The selected data is not being displayed

My input field is not displaying anything. Below is the script function in my view: <script> var Features = []; function LoadFeatures(element) { if(Features.length === 0) { $.ajax({ url:'@Url.Action("GetFeatures"," ...

Exploring the seamless integration of Next.js, TypeScript, and useContext across

Revision: I realized that I had forgotten to include the following line of code in my Header.tsx component: import Link from 'next/link'; After rectifying this oversight, everything started functioning properly. I am currently struggling with ...

Incorporate variable key-value pairs into a JavaScript array or object

Is it possible to add a key value pair to an existing JavaScript associative array using a variable as the key? I need this for JSON encoding and prefer a simple solution over using plugins or frameworks. ary.push({name: val}); In the above code snippet, ...

What could be causing my controller method in TypeScript to throw an error message unexpectedly?

Hey there. I'm diving into TypeScript and currently working on converting an Express backend to TS. Everything was smooth sailing until I encountered some unexpected issues. Specifically, the lines const hasVoted = poll.votedBy.some((voter): boolean = ...

Present information using Vue.js

Struggling to display just the name from the request object in my form using JavaScript. I'm new to working with JS and need some guidance. I attempted to use {{ request.name }}, but it's not functioning as expected. When I tried {{request}}, it ...

Error encountered in React JS: Unexpected token in syntax

Incorporating this code into my React application has been both rewarding and challenging. {this.state.display === true ? this.state.content.map((q) => { <Content id={q.id} key={q.id} content={q.content} ...

Receiving the result of a processed aspx page with a slight delay

My ASPX page contains some JavaScript code: <script> setTimeout("document.write('" + place.address + "');",1); </script> The issue arises when trying to retrieve the output from another page using a query string. Instead of gett ...

Encountering difficulties when serving assets in Express.js?

I am working with a file structure that looks like this: - server.js - controllers - [...] - public - utils - views - home - index.html - js - index.js - css - index.css When my application starts, I include ...

The Ajax URL is failing to connect with the controller through IIS

I am facing an issue where the application gets stuck in the Home controller when running it on IIS. It doesn't progress to the next controller (Data controller) as specified in the URL. However, when I run it in debug mode, everything works fine. How ...

Sending a notification alert directly to the client's web browser

My goal is to develop an application that allows Super users to notify other users by providing access to content, such as a PDF file, when they click on a link. For example, in the scenario where a teacher wants to share a PDF with students, this applica ...

Exploring User Authentication and Permissions in React and Node.js?

Currently working on a new application that utilizes the complete MERN stack, and I find myself at a crossroads when it comes to implementing protected routes, user authentication, and assigning ACL user roles. In past projects using Node.js, I've re ...

Babel Compile disrupts the flow of commands

I'm facing an issue while attempting to launch my development server after Babel successfully compiles my files. However, the command chain seems to halt right after Babel displays the compilation success message. Babel has completed compiling 82 f ...

Angular: Using ng-blur to toggle visibility between elements

I'm having trouble toggling the visibility of these divs: <div class="desc" ng-show="desc"> and displaying this div <div class="lists" ng-show="lists" ng-repeat="x in todoWork | orderBy:['todoPriority', 'todoTime&ap ...

Obtain the fabric js canvas object to enhance your designs

Currently, I am utilizing Fabric.js and have successfully created a fabric canvas object in one location. const myCanvas = new fabric.Canvas("canvasID"); Now, in another location, I need to access this canvas object but 'myCanvas' is not availa ...

Navigating through JQuery

Is there a way to scroll to a div + 100px specifically on the y axis? I am unsure how to achieve this. Can you provide guidance? I attempted using $.scrollTo('div100' + '100px', 2000) but unfortunately, it did not produce the desired ...

How can you add an error notification to a click on a protractor?

Is there a method to associate an error message with a protractor click function? I am envisioning something like the example line below: button.click('Button not clickable'); Currently, when an element cannot be located, I receive the non-spec ...