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

[Babel]: The option foreign.Children is not recognized

I encountered an error while building with the following script: webpack --colors --progress --watch --config --jsx-loader webpack.config.js Below is the content of my package.json file: { "dependencies": { // List of dependencies here }, "dev ...

The node command line does not recognize the term 'require'

My Typescript project was compiling and running smoothly until recently when I started encountering the error ReferenceError: require is not defined every time I try to run node. I am uncertain whether this issue stems from Typescript, as even when I ru ...

JavaScript: Transforming a key-value pair collection into an array of objects

I'm looking to convert a dictionary into a list of dictionaries using JavaScript. Can someone help me with that? var dict = { "apple" : 10, "banana" : 20, "orange" : 30 } var data = [ {"apple" : 10}, {"ban ...

Leverage Jasmine for testing a jQuery plugin

I'm currently utilizing the angular-minicolors library () within an angular controller: angular.element("myelement").minicolors({ position: 'top left', change: function() { //custom code to run upon color change } }) Wh ...

What do I need to add in order to connect a controller to a form submission?

Let's set the scene: There are multiple newsletter forms scattered across a webpage, all needing to perform the same action. This action involves making an AJAX request with certain data and displaying a message using an alert once the request is comp ...

Attempting to intercept a 401 error in an HTTP interceptor, I aim to refresh my session and then retry the initial request

My goal is to intercept responses returning from the /api, catching them if they are a 401 error, executing a refresh session action, and then retrying the original HTTP call again (while also preventing it from infinitely looping if another 401 error occu ...

NextImage's ImageProps is overriding src and alt properties

I've created a wrapper called IllustrationWrapper that I'm utilizing in different components. import Image, { ImageProps } from 'next/image'; const getImageUrl = (illustrationName: string) => { return `https://my-link.com/illustra ...

Angular Transclude - ng-repeat fails to iterate over elements

Recently, I've been experimenting with Angular directives and encountered a peculiar issue... Check out the code snippet below: <!DOCTYPE html> <html> <head> <title>Directive test</title> <script type="text/ja ...

Ways to implement a filter pipe on a property within an array of objects with an unspecified value

Currently, I'm tackling a project in Angular 8 and my data consists of an array of objects with various values: let studentArray = [ { Name: 'Anu', Mark: 50, IsPassed: true }, { Name: 'Raj', Mark: 20, IsPassed: false }, { Na ...

Troubleshooting problem with Zscaler and Ajax communication

When making an AJAX call on my website, everything runs smoothly except for when it is accessed behind a Zscaler proxy. In that case, the browser throws a CORS error: "No 'Access-Control-Allow-Origin' header is present on the requested resource. ...

The Art of Validating Configurations Using io-ts

I have recently switched to using io-ts instead of runtypes in a fresh project. In terms of configuration validation, my approach involves creating an object that specifies the types for each part of the config; const configTypeMap = { jwtSecret: t.str ...

Issue with esbuild not executing within docker compose configuration

Currently, I am new to using esbuild and struggling to set up a script that can watch and rebuild my files. Additionally, I need this functionality to work within a docker environment. Within my package.json file, the following scripts are defined: " ...

The module named "mongoose" does not have any member called 'PaginateResult' exported

I'm facing an issue while trying to add the necessary types for "mongoose-paginate" in my Angular 4 project setup with "angular-cli". The problem arises when Webpack throws an error. import {PaginateResult} from "mongoose"; ... getAll(page: number) ...

Ensure the date is displayed in the format of dd-mm-yyyy when using the input type=date

Here is the code I am currently using : <input type="date" class="form-control" id="training_date" name="training_date" placeholder=" select" value="" onfocus="(this.type='date')" onfocusout="(this.type='date')" max=<?php echo ...

Searching for real-time data with ajax. Strategies for showing alternative results when there is no user input

I am currently working on developing a live search feature using technologies like ajax, jQuery, PHP, and MySQL. The user inputs certain queries which are then sent to form_livesearch.php where the search is processed. I have successfully implemented this ...

Ways to eliminate numerous if statements in JavaScript programming

Here is the code snippet I'm working with: a = [] b = [] c = [] useEffect(() => { if(isEmpty(a) && isEmpty(b) && isEmpty(c)) { data.refetch() } if(data.isFetching){ //do something } if(response.isFetching){ //do som ...

Vue function that inserts <br> tags for addresses

My Vue filter retrieves and combines address details with a , Vue.filter('address', (address, countryNames = []) => { const formattedAddress = [ address?.name, address?.company, address?.add1, address?.add2, address?.town ...

The behavior of CSS position: sticky varies depending on whether the user is scrolling up or scrolling down

I am experiencing an issue in my Vue CLI app where a component with the position: sticky CSS property is being partially hidden under the top of the browser when scrolling down, but works correctly when scrolling up. This behavior is also observed on my Ga ...

Gather data from various HTML elements with JavaScript when submitting a form

How can I extract values from HTML elements and send them for processing through a form? I'm attempting to compile a menu item list with the individual items' structure in place, but I'm struggling to figure out how to fetch the values upon ...

Issue with react-addons-css-transition-group and multiline TextFields in Material-UI TextField

If a TextField with multiline is nested inside a react-addons-css-transition-group, it seems to disrupt the show transition. Any suggestions on how to handle this situation effectively? Check out my code snippet here: https://codesandbox.io/s/material-dem ...