What is the best way to retrieve distinct objects based on LocId across all locations?

Encountering an issue while working on Angular 7: unable to return distinct or unique objects based on LocId.

The goal is to retrieve unique objects from an array of objects containing all Locations.

allLocations:any[]=[];
ngOnInit()
{

this.locationsService.allLocations.forEach(loc => {
      let d = this.locationsService.allLocations.findIndex(x => x.Locid == loc.Locid);
      if (d !== -1) {
        this.locationsService.allLocations.splice(d, 1);
}

The HTML component code is as follows:

<tr *ngFor="let l of locationsService.allLocations">
                <td class="z2-boxstyle1-td-colcontent">
                  <div> {{l.Locid}} </div>
                </td>
</tr>

The current result of the array is:

[
{"Locid":40903,"GPS1":"42.5913974,-71.3277873","CompanyID":1000339},
{"Locid":40900,"GPS1":"42.588432,-71.31720900000001","CompanyID":1000339}
{"Locid":40900,"GPS1":"42.588432,-71.31720900000001","CompanyID":1000339}
]

Since the LocId is the same for two objects, I need to return only one distinct object as below:

Expected Result :

[
{"Locid":40903,"GPS1":"42.5913974,-71.3277873","CompanyID":1000339},
{"Locid":40900,"GPS1":"42.588432,-71.31720900000001","CompanyID":1000339}
]

Answer №1

The main issue here is that the sequence of elements in the array changes when you use .splice.

It seems like your goal is to avoid duplicating values.

You could achieve this by using .reduce like so:

var result = this.locationsService.allLocations.reduce((accumulator, value) => {
  if (!accumulator[value.Locid]) {
    accumulator[value.Locid] = value;
  }
return accumulator
},{});

console.log(Object.values(result));

Another approach is to create an empty list and add values from

this.locationsService.allLocations
only if the Locid is not already present in the list. (2-passes)

Alternatively, you can also utilize .filter and .findIndex for this task. (2-passes)

Overall, I would advise against these methods as they require two passes, whereas using .reduce with a single pass would be more efficient.

Answer №2

Filter the array by Locid

const uniqueArr = arr.filter((element, index, self) =>
  index === self.findIndex((t) => (t.Locid === element.Locid)));

console.log(uniqueArr);

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

Is it possible to verify if a string in JavaScript contains both numbers and special characters?

I created this function to check if a string contains numbers and special characters, but it seems to not be working correctly let validateStr = (stringToValidate) => { var pattern = /^[a-zA-Z]*$/; if (stringToValidate&& stringToValidate.leng ...

Tips for effectively using the JQuery animate function

Displayed below is my implementation of the jQuery animate method abstraction that works well. However, a challenge arises when trying to replace the hard-coded DOM element class in the function ani(){} with the 'this' keyword for versatility acr ...

Learn how to keep sessionStorage state synchronized across ReactJS components

Within my application, there is a React component responsible for displaying a list of numbers while also keeping track of the total sum of these numbers using sessionStorage. Additionally, another component provides an <input /> element to enable u ...

What is the equivalent of Buffer.from(<string>, 'hex') in Python?

I am currently facing the challenge of translating a Typescript library into Python. The specific library I am working with is bs58 in Typescript and its counterpart base58 in Python. My issue arises when attempting to replicate the following code: const ...

Including a hyperlink in VUE Bootstrap for seamless user navigation

Why does this always drive me crazy? I'm determined to include an external link () and an image(enter image description here) on my portfolio page within the title of the project. main.js { id: 18, url: 'single-portfolio. ...

JavaScript fails to display image slideshows upon loading

Currently, I am utilizing a slideshow feature in order to display any additional images that may be retrieved from the globalgiving api. However, there is an issue with the slideshow not appearing when the page is initially loaded or when opening a modal, ...

"Implementing x2js in your project on-the-fly with the help

Hey there, does anyone have the link for x2js that they could share with me? I'm interested in loading this JavaScript file dynamically. I tried using the code below but it didn't work: EffectaJQ.ajax({ async: false, url: "https ...

The function form.parse() in node.js is always overlooked

I'm having an issue where form.parse() is never called. When I delete bodyparser, my session variable throws an error. How can I resolve this and make it work? logcat The write(string, encoding, offset, length) method is deprecated. Use write(st ...

Is there a way for me to access the response from the PHP file I'm calling with Ajax?

I am just starting to explore ajax and jquery, and I recently found a code online that I'm tweaking for my own use. However, I am struggling with how to handle responses from PHP in this context. The current setup involves ajax POSTing to a php page ...

Creating dynamic keys using Typescript and JSON data format

Currently, I am developing an application using Typescript and React Native. Within my app, I have a JSON file containing information about poker hands that needs to be accessed. The structure of the JSON data is as follows: { "22": [ [ ...

When clicked, you will be redirected to the details page

Currently, I am developing a React JS application that showcases a list of companies fetched from a Node.js/Express server in a table format. When clicking on each row, it triggers a modal to display some details about the company. The modal consists of t ...

How to tell if one mesh is contained within another in Three.js

Currently, I am experimenting with Three.js and trying to figure out a way to check if one mesh is completely contained within another mesh. I've created a small robot that moves around inside a home box controlled by the player. While I know how to d ...

Iterating through a jQuery function to increment value

I have encountered an issue while trying to calculate the total value from an array of form fields. The problem lies in how the final value is being calculated on Keyup; it seems that only the last inputted value is being added instead of considering all t ...

How can we transform the `toUSD(amount)` function into a prototype function?

This function is functioning perfectly as intended. function toUSD(amount): string { // CONVERT number to $0.00 format return new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" }).format(amount); }; Here is how I currently i ...

Tips for showcasing information entered into text fields within a single container within another container

After creating three divs, the first being a parent div and the next two being child divs placed side by side, I encountered an issue with displaying input values. Specifically, I wanted to take values from input text boxes within the second div (floatchil ...

Yet another error: TS2511 - Unable to instantiate an abstract class

My issue is very similar to the one mentioned in this thread: Typescript: instance of an abstract class, however, there are some distinctions. If it is indeed a duplicate problem, I would appreciate a clear explanation as I am currently unable to resolve t ...

The 'flatMap' property is not found on the 'string[]' data type. This issue is not related to ES2019

A StackBlitz example that I have set up is failing to compile due to the usage of flatMap. The error message reads: Property 'flatMap' does not exist on type 'string[]'. Do you need to change your target library? Try changing the ' ...

Difficulty encountered when applying date filtering on a specific filter in the MUI-DataGrid

Software Version: "@mui/x-data-grid": "^6.2.1" I have a script that generates columns for the DataGrid as shown below (only including relevant code) if (prop === "date" || prop === "dateModified" || prop === "n ...

Tips for resolving issues with the carousel container in bootstrap?

Is there a way to adjust the carousel box container in Bootstrap so that it remains consistent even with images of varying sizes? Currently, the box size changes based on the image dimensions when sliding through the carousel. Sample Code: <h1>Caro ...

The link in Next.js is updating the URL but the page is not refreshing

I am facing a peculiar issue where a dynamic link within a component functions correctly in most areas of the site, but fails to work inside a specific React Component - Algolia InstantSearch (which is very similar in functionality to this example componen ...