Having trouble removing objects from a map results in having to invoke the function three times

I am facing an issue with the function findPrice where I need to call it multiple times to delete objects that match a specific price. The problem arises when dealing with large maps and two functions.

Here is the JSON format:

[ { _id: 5c6c408dbec3ab457cf5bdfb,
    date: 2019-02-19T00:00:00.000Z,
    user: 5c30fd5890bbd24a1c46c7ee,
    positionDetail: [ { quantity: 2, price:22}, { quantity: 3, price:33}, { quantity: 5, price:43}],
    id: 50,
    __v: 0 },
  { _id: 5c6c408dbec3ab457cf5bdfb,
    date: 2019-02-27T00:00:00.000Z,
    user: 5c30fd5890bbd24a1c46c7ee,
    positionDetail: [ { quantity: 3, price:33}, { quantity: 2, price:123}, { quantity: 2, price:11}],
    id: 51,
    __v: 0 }, ]

The issue seems to be related to the index of the map. I attempted to decrement 'i' when deleting an object from the map, but it did not yield the expected results.

findPrice() {

    this.arrayOfObjects.forEach( (data, i) => {

        let searchIfExist= data.positionsDetail.findIndex(index1 => index1.price === priceSearch);

        if (searchIfExist === -1) {

          this.arrayOfObjects.splice(i, 1);

          i--;
        }

    });
 }

Answer №1

Is there a better alternative to using Array.filter?

let filtered = this.arrayOfObjects.filter(data => data.positionDetail.price !== priceSearch);

Additional Note:

If you opt to use splice, it is recommended not to implement it within Array.forEach. Instead, consider using a for loop and iterate in reverse order (to maintain the array splice index)

for (let i = arrayOfObjects.length - 1; i >= 0; i--) {
  if (arrayOfObjects[i].positionDetail.price === priceSearch) {
    arrayOfObjects.splice(i, 1);
  }
}

In general, utilizing filter tends to be more efficient in terms of performance, as it does not alter the original array.

Additional Edit:

Is data.positionDetail treated as an Array? In that case, try this approach:

const filtered = this.arrayOfObjects.filter(data =>
  data.positionDetail.filter(
    priceData => priceData.price === priceSearch
  ).length !== 0
);

The inner filter operates on the positionDetail Array: if the outcome is empty, it indicates there is no price matching priceSearch, therefore the corresponding outer object is discarded.

Answer №2

To achieve your goal, implement array.filter or array.findIndex to identify the item with a price that does not match the specified pricesearch. Once identified, use the splice method to remove that item from the array.

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

The continuation of unraveling the mystery of utilizing `overflow-y:scroll` in a horizontal slider

As a beginner, I realized too late that adding code in comments is not an option. Consequently, I decided to create a new question and ask for your assistance once again. To optimize the use of space, I have implemented bxSlider with fixed dimensions (wid ...

Tips for adjusting the selected value in the ng2-select feature

I'm currently developing an angular2 application and I've integrated ng2-select for the multiselect dropdown feature. Everything works smoothly when creating a new entry, however, I'm facing issues with setting default selected values pulled ...

Creating a variable to store the data retrieved from a package

Imagine you have a functioning code snippet like this: const myPackage = require('myPackage'); myPackage.internal_func(parameter).then(console.log); This outputs a JSON object, for example: { x: 'valX', y: 'valY' } ...

The sequence of initializing test hooks in inconsistent playwright tests

My testing framework setup looks something like this: test.describe("...", () => { let p: Page; test.beforeEach(async({browser}) => { p = await (await browser.newContext()).newPage(); } test(...); test(...); test.aft ...

When the Button is clicked, the component utilizing the Router fails to appear

My current task involves creating a page where users can choose between two options: Button 1 leads to TestOption.js, while Button 2 redirects to TestOption2 (currently using TestOption for testing purposes). The default landing page is SelectionPage. The ...

Encounter an error message "Expected 0 type arguments, but received 1.ts(2558)" while utilizing useContext within a TypeScript setting

Encountering the error mentioned in the title on useContext<IDBDatabaseContext> due to the code snippet below: interface IDBDatabaseContext { db: IDBDatabase | null } const DBcontext = createContext<IDBDatabaseContext>({db: null}) Despite s ...

Investigate issues with POST data requests

I recently utilized a REST API to send a POST request. Upon clicking on the function addmode(), a textbox is displayed allowing users to input data. However, upon clicking the save() button, an unexpected error occurs and redirects to a PUT Request. Using ...

What is the best approach for handling an AJAX request on the server side?

Consider the function below: $.ajax({url:"http://127.0.0.1:8080", data: "123", success: function(response, textStatus, jqXHR) { alert(response); }, error: function(jqXHR, textStatus, errorThrown) { alert("An er ...

Querying with a TypeORM many-to-many relationship

Entity Program: export abstract class ProgramBase { @Column('varchar') programName: string; @Column('text') programDescription: string; @Column({ type: 'boolean', default: false }) isDeleted: boolean; @Column( ...

Filtering without the includes() Method

I have two Objects that are structured as follows: export const recipes: Recipe[] = [ new Recipe( id: "Green", scenario: ["1", "2"]), new Recipe( id: "Blue", scenario: ["1", "2","2"]) ]; export const scenarios: Scenario[] = [ new Scenario( id: "1 ...

What is the significance of utilizing an empty value `[]` for a typed array interface instead of using an empty `{}` for a typed object interface?

Why can I initialize friends below as an empty array [], but not do the same for session with an empty object {}? Is there a way to use the empty object without needing to make all keys optional in the interface? const initialState: { friends: Array< ...

Exiting or returning from a $scope function in AngularJS: a guide

There are times when I need to exit from my $scope function based on a certain condition. I have attempted to achieve this using the return statement. However, my efforts have been in vain as it only exits from the current loop and not from the main scop ...

Participants will utilize functions to predict a number between 1 and 1000

I am currently working on a project that involves creating a number guessing game for the user. The idea is to have the program generate a random number between 1 and 1000, and then prompt the user to guess the number. If the guess is too low or too high ...

Error: Undefined Property in Angular 2 ViewChild Declaration

Exploring a simple example where the childMethod is called within the child component from the parent component using the @ViewChild() decorator. However, encountering an issue where the ViewChild variable remains undefined. Sample Child Component Code: ...

How to Calculate Dates in Javascript

Currently exploring the realm of JavaScript, I find myself in the process of developing a dashboard for an e-commerce platform that I am currently involved with. My goal is to display data for all dates starting from the date of the initial order placed. M ...

Vue.js does not support sorting columns

In this specific codepen example, I have created a Vue table that allows for sorting by clicking on the column name. Although I can successfully retrieve the column name in the function and log it to the console, the columns are not sorting as expected. Wh ...

Find with user-friendly input/label removal function (Ionic 2)

I have embarked on creating a recipe application where users can search for recipes by ingredients. I want to enhance the functionality of the search feature so that when users press the spacebar to enter the next input, it appears as a label below with an ...

Enable users to provide ratings ranging from 0.5 up to 5

I recently created a rating component that allows users to rate on a scale from 0 to 4.5, with increments of 0.5, which is causing unexpected behavior. I actually want users to be able to rate from 0.5 to 5 instead. How can I achieve this adjustment? Below ...

Tips for overcoming a script error within the body of a Next.js project

I encountered an error in my _document.js file when trying to add a script to the body of my document. Here is the specific error message that was returned: https://i.stack.imgur.com/QG5zb.png ./pages/_document.js Error: x Expected '}', got &a ...

Issue encountered in Next.JS when attempting to validate for the presence of 'window == undefined': Hydration process failed due to inconsistencies between the initial UI and the server-rendered

I encountered an issue that says: Hydration failed because the initial UI does not match what was rendered on the server. My code involves getServerSideProps and includes a check within the page to determine if it is running in the browser (window==&apo ...