Stop an item from being included based on a boolean value

I need to iterate through an array of IDs called "world". The idea is that if the ID value in world exists in myArray[n].id, then I want to remove the entire element from myArray. If it doesn't exist, then I want to add it to myArray.

world = ["12424126","12461667","12492468","12761163"]

myArray = [
{"id": "12424126"},
{"id": "12761163"},
{"id": "12492468"}
]

For example, if the first element in world[n] ("12424126") matches { "id": "12424126" } in myArray, I should delete the element { "id": "12424126" }

If the first element in world[n] ("12424126") does not exist in myArray:

myArray.push ({ "id": world[n] }); 
}

for (let n = 0; n <= world.length; n++) {

let ID = world[n]; 

finished = false;

if (myArray.find(x => x.id === ID)) {
let index = _.findIndex(myArray, { "id": ID });
if (index > -1) { myArray.splice(index, 1);
finished = true;}
}

if (!finished) // ISSUE: RECORD GETS ADDED REGARDLESS OF FINISHED TRUE/FALSE
{myArray.push ({ id: ID }); // HOW CAN I SOLVE THIS PROBLEM?
}

}

Answer №1

This code snippet accomplishes the desired functionality

planet = ["34567890", "34765678", "34563345", "34123456"];

myList = [{ id: "34567890" }, { id: "34123456" }, { id: "34563345" }];
for (i = 0; i < planet.length; i++) {
  ID = planet[i];

  var position = myList.findIndex((element) => element.id == ID);
  if (position > -1) {
    myList.splice(position, 1);
  } else {
    myList.push({ id: ID });
  }
}

Answer №2

The issue lies in the loop causing finished to switch back from true to false in subsequent iterations. To resolve this, you should exit the loop immediately upon setting finished to true.

An alternative solution involves using a Set:

const world = ["12424126","12461667","12492468","12761163"];
let myArray = [{"id": "12424126"},{"id": "12761163"},{"id": "12492468"}];

const set = new Set(myArray.map(({id}) => id).concat(world));
myArray = Array.from(set, id => ({id}));

console.log(myArray);

If you prefer not to create a new array for myArray, and avoid generating new objects for existing ones, then:

const world = ["12424126","12461667","12492468","12761163"];
let myArray = [{"id": "12424126"},{"id": "12761163"},{"id": "12492468"}];

const set = new Set(myArray.map(({id}) => id).concat(world));
myArray.push(...Array.from(set).slice(myArray.length).map(id => ({id})));

console.log(myArray);

However, this approach assumes that myArray did not initially contain duplicate id values.

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

Loading data dynamically in a table by utilizing the react WayPoint library

I'm currently utilizing a combination of material UI table and react-table. When the number of rows in the table exceeds around 200, the performance dips. To address this issue, I am looking to display a fixed number of rows (let's say 20 rows) i ...

Combining default and named exports in Rollup configuration

Currently, I am in the process of developing a Bluetooth library for Node.js which will be utilizing TypeScript and Rollup. My goal is to allow users to import components from my library in various ways. import Sblendid from "@sblendid/sblendid"; import S ...

Using jQuery to retrieve the values of two distinct sliders and executing a specific mathematical operation

I have two sliders with their own values and properties: https://i.stack.imgur.com/3OZqr.gif My goal is to retrieve the values of these two sliders and calculate a result that will be displayed next to the interest label. The calculation formula is: poun ...

Angular is not programmed to automatically reflect updates made to my string array

let signalRServerEndPoint = 'https://localhost:44338'; this.connection = $.hubConnection(signalRServerEndPoint); this.proxy = this.connection.createHubProxy('MessagesHub'); this.proxy.on("ReceiveMessage", (message) => { ...

Two interconnected queries with the second query relying on the results of the first

I am currently facing a challenge in my Phonegap (Cordova) application where I need to display a list of items, each requiring an additional query. Let me simplify it with an example scenario. Imagine a student can be enrolled in multiple courses and a co ...

Mask the "null" data in JSON

I'm currently working with a JSON file and trying to display it in a bootstrap table. Check out the code snippet I've been using: $(document).ready(function(){ $.getJSON(url, function(data){ content = '<h1><p class="p1 ...

Loading an ASP.net page on the client side

Can someone tell me the event for pageload on clientside? function onPageLoad() { setSelectedIndexTo(1); } I attempted to do this, however no changes occur. Appreciate any help. Thanks! ...

What makes styling a success button in @material-ui so challenging?

I am currently utilizing the user interface framework found at https://material-ui.com/ My primary aim is to obtain a success Button and Chip. Can anyone provide insight on achieving this goal without resorting to less-than-ideal methods like those discus ...

A Vue element that has multiple exact click handlers will consistently trigger the click.exact method when clicked with system modifiers

According to the information found at https://v2.vuejs.org/v2/guide/events.html#exact-Modifier, I am attempting to build an element that triggers different methods based on additional keys pressed at the time of clicking. <span @click.exact="method ...

What is the best way to incorporate a new attribute into an array of JSON objects in React by leveraging function components and referencing another array?

Still learning the ropes of JavaScript and React. Currently facing a bit of a roadblock with the basic react/JavaScript syntax. Here's what I'm trying to accomplish: import axios from 'axios'; import React, { useState, useEffect, useMe ...

Error in Redux reducer file caused by an incorrect data type in action.payload

I have encountered a type error in my reducers' file where it says that my 'Property 'address' does not exist on type 'number | { connection: boolean; address: string; }'. This issue is arising in my React application while us ...

Customizing the Switch component individually for each item fetched from an API in React Native

I'm struggling with setting the switch button individually for each item in my API. Despite trying multiple solutions, none of them seem to work for me. const results = [ { Id: "IySO9wUrt8", Name: & ...

Creating a paragraph from text inputs using React

I'm currently working on code that retrieves input from two textboxes - one for a string value and one for a number value. I want this data to be displayed in real-time within a paragraph without the need for a submit button. I've been struggling ...

What is the best way to send an HTML form variable to a Perl script using AJAX?

My goal is to pass the HTML variable from the list menu to the Perl script using POST. However, when I try to do this, the jQuery ajax() function executes the Perl script without including the value obtained from document.getElementById. Below is the sni ...

TypeError thrown by Mapbox markers

Looking to incorporate markers into my map using Mapbox. Below is the Angular TypeScript code I am working with: export class MappViewComponent implements OnInit { map: mapboxgl.Map; lat = 41.1293; lng = -8.4464; style = "mapbox://styles/mapb ...

Customize the appearance of a shadow-root element

Is there a way to modify the styles of a shadow element? Specifically, is it possible to extend or overwrite certain properties within a CSS class? I am currently using a Chrome extension called Beanote, which has not been updated since April 2017. There i ...

Tips for storing and replicating jQuery events

I am working on saving jQuery events in a database. // This Function is called On Click function trackevent(event){ window.events.push(event) } $.each(window.events, function(i, item){ console.log(i +" - "+ $.parseJSON(item)); }); The events a ...

When the user clicks on the iframe, they will be redirected to the

My goal is to create a scenario where clicking on an iframe opens the same URL in a new browser tab, while ensuring that scroll and other mouse events within the iframe are not affected. I have experimented with various approaches but none have been succe ...

Nginx and Socket.io: Issues with client-server connection not functioning properly

Hello everyone! I am currently in the process of deploying my application, which utilizes React and NodeJs. However, I have encountered an issue with integrating Socket.io with Nginx. My approach involves editing the Nginx file using the command: sudo ...

Angular.js reports that the custom HTTP response header is missing

Despite Chrome showing the correct POST response headers, my custom HTTP header X-Auth-Token is returning null in the callback function for the POST request. Angular.js seems to only be returning Cache-Control and Content-Type, with everything else showing ...