The map() function's splice operation unexpectedly removes only half of the array

I am currently working with an array that contains 146 objects, each object having its own unique id. My goal is to delete any objects from the array that do not have a matching id. I wrote a function to accomplish this task, however, it only works for half of the array. The function was functioning correctly before I implemented the splice method. Here is my code:

getFullData(){
var fullData = [OBJECTS].sort(function(a,b){if(a.date<b.date)return 1; if(a.date > b.date) return -1})} //sorting

fullData.map(val=>{
  Object.assign(val, {dataType:this.getDateType(val.date)}); //this line not about these problem
  if (val.device !== this.id) {
    fullData.splice(fullData.indexOf(val), 1);
  }  
});
return fullData;
}

All ids on the objects are currently the same. If I route a different id using the router, all objects should be deleted, but only 73 are being removed.

Answer №1

To optimize the loop process when splicing an array, consider using a filter before mapping over it:

fullData = fullData
  .filter((val) => val.device !== this.id)
  .map((val) => {...val, dataType: this.getDateType(val.date) });

If you are concerned about performance and want to avoid looping twice, you can combine both operations within the filter function:

fullData = fullData
  .filter((val) => {
    if (val.device !== this.id) {
      return false;
    }

    val.dataType = this.getDateType(val.date);

    return true;
  })

Answer №2

Opt for using the filter function rather than splice within map.

let filteredData = fullData.filter(item => item.device === yourId)

//filteredData array will only include items from fullData where the device value is equal to yourId

Explore more on filter

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

In order to maintain a custom tooltip in an open state until it is hovered over, while also controlling its

When hovering over the first column of the table, a tooltip will appear. Within each material tooltip, I would like to include a button at the bottom right after the JSON data. When this button is clicked, it should open an Angular Material dialog. <ng ...

What is the best way to exclude an interface using a union type recursively in TypeScript?

I wish to recursively exclude types that are part of union types, and eliminate certain union types Here is an example. Normal and Admin should be considered as union types interface Admin { admin: never; } interface Normal { normal: never; } ...

Issue with Angular Filters: Difficulty Arises When Search Box is Cleared

I have a list of objects that I am displaying, and I added a search box to filter a column. When I enter a value, the data is filtered correctly. However, when I clear the search box, I do not get all the data back; I remain stuck with the initially search ...

Trouble arises when trying to test an Angular service that relies on abstract class dependencies

Currently, I am working on a service that has a dependency on another service, which in turn relies on two abstract classes as dependencies. (ThemeConfigService -> (SettingsService -> SettingsLoader, NavigationLoader)) During testing, the failure oc ...

Combining declarations with a personalized interface using TypeScript

My goal is to enhance the express.Request type by adding a user property so that req.user will be of my custom IUser type. After learning about declaration merging, I decided to create a custom.d.ts file. declare namespace Express { export interface ...

Can you identify the TypeScript type for an array containing various Angular components?

In my application, I have a diverse range of components that I would like to organize into an array. There are no restrictions on what types of components can be included in this array, as long as they are Angular components. What is the correct way to de ...

What are the steps to integrate TypeScript into JavaScript code?

How can I import a TypeScript class in a Node CommonJS JavaScript file? When using mongoose in my TypeScript code, I typically do the following: // user.model.ts export const UserModel = model<User>('User', schema); In my JavaScript code: ...

Retrieve the raw text from the input field instead of the date object

Below is the HTML code for an input field: <div class="input-group input-group-md"> <input id="date" name="date" [readOnly]="disabled" type="text" placeholder="M0/d0/0000 Hh:m0:s0" [placeholder]="pl ...

Tips for implementing collapsible functionality that activates only when a specific row is clicked

I need to update the functionality so that when I click on a row icon, only that specific row collapses and displays its data. Currently, when I click on any row in the table, it expands all rows to display their content. {data.map((dataRow ...

Adding an external JavaScript file to an Angular 5.0.0 project

Struggling to integrate hello.js into my Angular 5.0.2 project. See the CLI version below https://i.sstatic.net/RcGz5.jpg I have included the script file in angular-cli.json. "scripts": [ "./js/hello.js", "./js/hello.polyfill.js", ...

Is it considered an anti-pattern for certain components within a tile system to share a viewmodel when the parent web component has multiple child components?

Creating an Angular application involves a parent component that contains child components. I am looking for a way to share functionality among the components without resorting to creating services for each one. One approach would be to build services and ...

Unable to transmit props while employing Typescript in ReactJS

Attempting to pass props from components like AllProducts, MenProducts, etc. to the AddToCartButton component for reusability presents a challenge. When trying to pass props using: <AddToCartButton id={product.id} /> An error is encountered: Type & ...

Link the Angular Material Table to a basic array

Currently facing a challenge with the Angular Material table implementation. Struggling to comprehend everything... I am looking to link my AngularApp with a robot that sends me information in a "datas" array. To display my array, I utilized the following ...

Display JSX using the material-ui Button component when it is clicked

When I click on a material-ui button, I'm attempting to render JSX. Despite logging to the console when clicking, none of the JSX is being displayed. interface TileProps { address?: string; } const renderDisplayer = (address: string) => { ...

Finding a solution to this issue in Angular will consistently result in a false outcome

Can anyone explain why I keep getting the error message "This condition will always return 'false' since the types 'typeof ChartType' and 'ChartType' have no overlap" whenever I try to compare charTypeEnum with ChartType.text? ...

Upgrading the import package alias from 'angular2' to '@angular'

Is there a way to update the package alias for import purposes? I am trying to utilize ng2-bootstrap, which requires @angular/core, but I have been referencing it as angular2/core. This mismatch is causing my screen to crash! ...

Angular 4: The Authguard (canActivate) is failing to effectively block the URL, causing the app to break and preventing access to all resources. Surprisingly, no errors are being

I have created an authguard, but it seems to not be blocking the route when the user is logged out. The authentication workflow in the app works fine, as I am using traditional sessions on the backend database. I have also verified the state of the auth se ...

In order to toggle the input field's state depending on the select component's value in Angular

I have a situation with two components: a select component and an input component, as shown in the image below: https://i.sstatic.net/rjjEn.png Scenario: Currently, the input field is disabled by default. If an option is selected from the select componen ...

Using Angular (along with Typescript) to showcase JSON data

I previously shared this query, but unfortunately, I didn't receive many helpful responses I have a JSON file that holds the following dataset: [{ "ID": 1030980, "Component": "Glikoza (Gluk)", "Result": "16", "Date": "20.10.2018" } ...

Troubleshooting issue: Angular Typescript object array filter functionality malfunctioning

I am currently attempting to filter an array of objects based on a specific value. Interestingly, out of the console.log outputs provided below, only the first one is yielding the expected result: console.log('log1: ', sf); console.log('log ...