JavaScript loop that removes the first matching element in an array

My array of Exclusions is structured as shown below:

Exclusions: [ID:"233242", Loc:"West", ID:"322234" , Loc:"South"]

Within my Object, I have a nested array of objects that resembles:

Schools : [ O: [ ID:"233242" ] , 1:[ ID:"233242"] , 2: [ID :"954944"] ] 

I am looking to remove any matching array indices with the same ID as in the Exclusions array, but only for the first match. This means that the element at index 0 should be deleted, while the element at index 1 should remain. How should I adjust my loop for this:

$.each(Exclusions, function (index, value) {
    var loc = value.Loc;
    var ID = value.ID;
    Object.keys(Schools.District.Pack[loc]).forEach(function (key) {
        //need to iterate through the entire object
        if (Schools.District.Pack[loc].ID === ID) {
            //remove the first match and stop searching
            Schools.District.Pack[loc].splice(key, 1);

            //break; this is incorrect
        }
    });
});

Answer №1

If you want to efficiently handle removed IDs, consider adding another lookup array specifically for them. Here's a possible solution:

var Excluded = [{ID:"233242", Loc:"West"}, {ID:"322234" , Loc:"South"}];
var Schools = [{ ID:"233242" } ,{ ID:"233242"} , {ID :"954944"} ];

var removedKeys = [];

$.each(Excluded, function (index, value) {
    var loc = value.Loc;
    var ID = value.ID;
    Object.keys(Schools).forEach(function (key) {
        if ((Schools[key].ID === ID) && (removedKeys.indexOf(ID) == -1)) {
            removedKeys.push(ID);
            delete Schools[key];
        }
    });    
});
console.log(removedKeys);
console.log(Schools);

Feel free to check out the fiddle for a live demo

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

Tips for inserting a component into a div selector using Angular 2

Could someone please help me figure out how to inject a component into a div selector using a class or id? I'm familiar with injecting components into other components, but not sure how to do it specifically within a div. Any guidance would be greatly ...

methods to retrieve value from a javascript function

Just a quick inquiry - what's the best way to pass or return a value from a function? Here is my code: function numberOfDivs(){ var numberOfElements = $("#div").children().length; // Counting the number of existing divs return numberOfElements; } ...

When attempting to access the length of a JSON array, it results in undefined

I recently received a JSON encoded array from an AJAX call that looks like this: {"country":{"0":"United States of America","United States of America":{"states":{"0":"Alaska","Alaska":{"cities":["Adak","Akiachak","Akiak","Akutan","Alakanuk"]}}}}} Below ...

The React component is failing to display updated data from the Redux store

I've been working with React and Redux, trying to update my counter value in the React view. I can successfully log the latest state of my Redux store, but the changes are not reflecting in my React view. const counter = (state = 0, action) => { ...

How can I utilize passed in parameters in Meteor React?

I am trying to figure out how to use two params that I have passed in the following example. Can someone please assist me? updater(layer, item){ this.setState({layer5: <img id="layer5" className="on-top img-responsive center-block" name="layer5" ...

Troubleshooting challenges with updating Ajax (SQL and add-ons)

I am currently facing some specific issues with an ajax update feature, but I am confident that it just requires some fine-tuning to work perfectly. Below, I will outline the problems clearly: In my setup, there are two files that interact with each othe ...

Using axiosjs to send FormData from a Node.js environment

I am facing an issue with making the post request correctly using Flightaware's API, which requires form data. Since Node does not support form data, I decided to import form-data from this link. Here is how my code looks like with axios. import { Fl ...

Angular: Understanding Render Delay Caused by *ngIf and Expression Changes from Filters

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'ngIf: false'. Current value: 'ngIf: true'. Encountering the above error in the console. In my code, I have filters that control ...

Merging JSON array with a different dataset

I have data in an array format like [1,2,3] and I am trying to join it with another table. This is the query I am using: select RCM.header_details->'auditAssertion' as auditassertion from masters."RCM" RCM left join reference."AUDIT_A ...

Prevent the automatic inflation of bubbles on the D3 World Map

Currently, I am developing a D3 world map with a zoom feature that allows users to zoom in up to the boundary level of any country or county by clicking on it. I have successfully added bubbles that point to various counties in Kenya, and these bubbles en ...

I am experiencing issues with icons not loading correctly after changing my module, with error messages indicating issues with cross-origin

Exploring various online tutorials to master the art of Angular programming has been quite an adventure for me. One tutorial introduced a module defined in this manner: .module('MyApp') However, any attempt to modify the name resulted in an er ...

What could be causing the issue with the initialization of useState not working as expected?

I have the following React code snippet: import React, { useState, useEffect } from "react"; import axios from "axios"; function App() { const [players, setPlayers] = useState([]); // Fetch all Players const getAllPlayersUrl = & ...

A guide on triggering a function in Angular 6 when scrolling up or down

Is there a way to trigger a function when a user scrolls up or down in an Angular 6 project? I want to implement a feature similar to fullpage.js in my Angular 6 application. I initially attempted to achieve this using Angular animations, but without succ ...

Tips for displaying a jQuery error message when a key is pressed

I am working with a textarea that has a word count limit of 500. I need to display an error message below the textarea if the word count exceeds 500. I have successfully calculated the word count, but I am unsure how to display the error message and preve ...

How can you leverage the power of useState in a custom React hook?

Here is a code snippet for a custom hook I created: const useShowBg = () => { const [showBg, useShowBg] = useState(false); return [showBg, useShowBg]; }; export default useShowBg; In my component, I import and use the custom hook like this: im ...

The font size of the textarea dynamically adjusts based on the size of the screen

Some strange behavior is occurring in the Android default browser when I set the width and height of a textarea to 100%. The font size of the textarea seems to increase based on the screen size, and even though I attempted to alert the font-size using jQue ...

How can I dynamically update a div without refreshing the page by using an onclick event on a

When working on my project, I found helpful insights from this Stack Overflow thread. The structure of template-comparison.php involves fetching code from header.php to ensure the page displays properly. However, the actual "fetch code" process remains un ...

What is the method to combine multiple style values in vue.js?

Is there a way to create a div with a box shadow where the values can be changed using a slider? I am having trouble using more than one value stored in a data variable. Any suggestions on how to achieve this? <div :style="{ borderRadius: x_axis y_ ...

Achieving cell merging in react-table can be accomplished by utilizing the appropriate

Currently, I am using react-table and have the need to combine cells in specific columns based on their content. Essentially, I want to remove the divider border between these merged cells. To give you a visual idea, this is how it currently looks like: h ...

React TypeScript with ForwardRef feature is causing an error: Property 'ref' is not found in type 'IntrinsicAttributes'

After spending a considerable amount of time grappling with typings and forwardRefs in React and TypeScript, I am really hoping someone can help clarify things for me. I am currently working on a DataList component that consists of three main parts: A Co ...