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

Adding next-auth middleware on top of nextjs middleware in Nextjs implementation

I am in need of the nextjs middleware to be activated for two distinct paths: Firstly, to serve as a protection against unauthorized access by utilizing next-auth. Secondly, to redirect authorized users from specific pages. For example, if an authorized u ...

Attempting to utilize express-load in conjunction with express 4

As a beginner in NodeJS, I encountered a problem with my code. Let me show you the issue. I am trying to load the application in the MVC pattern using express-load, but I am facing an error when defining the load order. Here is the important part of app. ...

Combining data from various JSON files to create dynamic charts with Highcharts

At this moment, my Highchart code is set up in a way where I want to replace the static data-series values within the HTML file with information loaded from a JSON file. The current code appears as follows: <!doctype html> <script type="text/jav ...

What is the process for displaying all indexes of a Mongo Collection using MongoDB Node native?

I am curious about how to retrieve all indexes from a specific collection in mongodb. I've tried using listIndexes, indexes, and indexInformation, but these methods only return empty values (arrays and objects). However, when I run db.getCollection(&a ...

Submitting forms from a different router in React can pose a unique challenge

As a beginner in React, I am working on creating a simple meal app. In my App component, I am fetching meal data from an api and allowing users to click on a meal for more details. However, I am facing an issue where searching for a new meal on the detail ...

Experience running two functions simultaneously in jQuery simulation

Presented here are two functions that I am working with: loadTop(); loadBottom(); One of these functions is responsible for loading the top portion of a page while the other takes care of loading the bottom. The loadTop function involves asynchronous o ...

Failure of AJAX HTML function to retrieve value from textarea

I am displaying data in the first three columns of a table, with the last column reserved for user feedback/comments. However, when the form is submitted, the values in the textarea are not being posted. The table has 6 rows. The Sample TR: <tr> &l ...

Updating values in mongoDB using Express.js and axios: A step-by-step guide

I need help figuring out how to update a specific post's data in my mongoDB using its object id. I have created an HTML form that displays the selected post's data and allows me to make changes, then submit the updated data to http://localhost:50 ...

Ways to verify if Arabic text has been submitted by the user through a form?

Is there a foolproof method for detecting Arabic input in a form before submission? Can Javascript effectively manage this task, or is it better handled by server-side scripts like .NET? I propose implementing a script to immediately block users from ente ...

Exploring the integration of Glide js within a Next js environment

I am trying to figure out how to use a script tag in the next JavaScript _app.js component for utilizing the Glide JavaScript carousel. However, I am facing difficulties in using the script tag. Can someone help me out by providing guidance on how to inc ...

Utilize HTML5 to enable fullscreen functionality for embedded SWF files

I have implemented a function that handles the click event of a button to toggle a DOM element into fullscreen mode. The function works well, but I am facing an issue when there is another div containing a swf inside the main div. var elem = document.getE ...

Tips for transforming a JSON array into a JavaScript 2D array

I am struggling to figure out how to convert the given JSON data into a JS 2D array directly from HTML. [{"fields": {"diameter": 23.0, "neighbourhood": "WEST END"}, "model": "hug.tree", "pk": 345}, {"fields": {"diameter": 14.0, "neighbourhood": "MOUNT P ...

Different techniques for using percentages in CSS transformations to create dynamic animations for DOM element translations

I have 14 objects positioned across the dom that I need to animate using the translate property. Currently, I am using transform: translate(x%, y%) for each object, requiring me to calculate the translation amount and apply a CSS style individually. This m ...

What is the best way to retrieve the value of the first name using Protractor?

Is there a way to store the value of the first name using a protractor script? The first name is set when the user logs in and corresponds to the name of the logged-in user. I am wondering if this can be done utilizing by.addLocator(). Here is the tag tha ...

Determine the maximum array size in Javascript

Having trouble setting a limit in my custom lightbox for a gallery <script> var imagenumber = 0; function btnleft(){ load = imagenumber-=1; document.getElementById('lightboxcontent').innerHTML=imagelist[load]; ...

Using Multithreading and the Subscribe/Publish Methodology in JavaScript

Is it true that JavaScript does not support multithreading? I am seeking expert advice on a specific scenario. I need to make an AJAX call and upon successful completion, trigger a set of events to update different parts of the UI simultaneously. Would ...

Is it necessary to clear out older node.js sessions that are saved in a database?

After incorporating a database session storage for my node application, I noticed that abandoned sessions could potentially linger in the database indefinitely if a user never returns to the application or clears their cookies. Would it be advisable for m ...

Unable to view new content as window does not scroll when content fills it up

As I work on developing a roulette system program (more to deter me from betting than to actually bet!), I've encountered an issue with the main window '#results' not scrolling when filled with results. The scroll should always follow the la ...

What is the best way to save the outcomes of several asynchronous $.get calls into an array?

I have a challenge where I need to retrieve data from an API for each item in an array, and then store that data in another array for further processing. However, I suspect the issue lies in the asynchronous nature of the requests, as the data may not be ...

Uploading a file to a .NET Framework API Controller using React

I am trying to figure out how to send files in the request body to an API controller in .NET framework using React. My goal is to achieve this without changing the request headers, so I want to send it as application/json. What I am looking for is somethi ...