What is the best way to remove an element from an array and add a new one?

Here is the array that I am working with:

 [
  {
   "id": "z12",
   "val": "lu",
   "val2": "1",
  },
  {
   "id": "z13",
   "val": "la",
   "val2": "2",
  },
  {
   "id": "z14",
   "val": "lo",
   "val2": "3",
  },
]

Additionally, I have a second array called array2 which looks like this:

    array2 = {
      tab: [],
    }

In my TypeScript code, I perform the following operation on the arrays:

   array.forEach((item, index)=>{
    if(item.id === z12){
      array.splice(index, 1);
    }else{
      array2.tab.push(item.id);
    }
});

The expected result should be having tab: [z13,z14], however it is not producing the desired outcome.

Answer №1

You can perform filtering and mapping operations directly on arrays in JavaScript.

const data = [{ "id": "z12", "val": "lu", "val2": "1", }, { "id": "z13", "val": "la", "val2": "2", }, { "id": "z14", "val": "lo", "val2": "3", },];

const newData = {
  modifiedArray: data.filter(item => item['id'] != "z12").map(item => item['id']),
}

console.log(newData)

Answer №2

To achieve this, you might consider breaking it down into two separate steps:

// Begin by filtering out the element with id 'z12' as per your request
array = array.filter(item => item.id !== 'z12')

// Then create a new object containing only the remaining ids
remainingIds = {
  tab: array.map(item => item.id)
}

Answer №3

Using the splice() method within a forEach() loop can lead to unexpected issues. In a scenario where "z12" is removed from an array, the resulting array will look like this:

 [
  {
   "id": "z13",
   "val": "la",
   "val2": "2",
  },
  {
   "id": "z14",
   "val": "lo",
   "val2": "3",
  },
]

However, it's important to note that the iteration of the forEach method does not automatically stop itself. It will continue with index 1 right after "z12" was removed, making the item at index 1 now refer to "z14" instead of "z13".

If you want to learn more about best practices for using forEach, check out this video: Why forEach is BAD!

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

Passing a callback to a third-party library resulted in an unexpected error

My React+TypeScript code utilizes a component from a third-party library. <ThirdPartyComponent onSelect={(value: any) => {...}} /> The eslint-typescript tool is flagging this as an error: Unexpected any. Specify a different type. eslint(@type ...

Accessing clipboard contents upon button click using TypeScript

Seeking assistance with retrieving data from the clipboard in TypeScript after clicking on a button. Please provide guidance. Thank you! ...

switch the anchor tag value and send it along with the URL

I am trying to update the value of "trans" in the Ajax URL based on a toggle between on and off values. However, despite successfully toggling the text, the URL parameter does not change accordingly. Can anyone offer any assistance? I currently have to rel ...

The margin persists despite the usage of the * selector and !important declaration

I'm currently working on a website built upon this template: https://github.com/issaafalkattan/React-Landing-Page-Template My issue arises when trying to remove margins in multiple sections. For instance, I want to eliminate the 'orange' ar ...

waiting for udp response in node.js using express

Currently, I am diving into the world of node.js programming and have encountered a challenge. While working with express, I came across an issue. When a POST request is made, it triggers a radius authentication process over UDP using the dgram module. Ho ...

Utilizing HTTPS for OpenWeatherMap API in JavaScript encounters obstruction

I'm currently working on a project with free code camp where I am attempting to create a weather app using the OpenWeatherMap API. However, I have encountered an issue. My project needs to be submitted on Codepen and use HTTPS for geolocation. Due to ...

Exploring a one-dimensional nested array in order to make updates to the higher level nodes

I have a 1D nested array: nestedArr: [ { id: 1, parentId: null, taskCode: '12', taskName: 'Parent', duration: 0, assignee: '', crewCount: 0, startDate: null, endDate: null, dependencies: []}, { id: 2, parentId: 1, taskCo ...

Using JSDoc and Visual Studio Code: Writing documentation for a function that is being passed as an argument to another

Struggling to properly document the input parameters for a JavaScript function using JSDoc. The documentation suggests using the @callback comment, but Visual Studio Code (VSCode) doesn't seem to recognize it. In VSCode, the intellisense for the loca ...

Utilizing Selenium Webdriver to efficiently scroll through a webpage with AJAX-loaded content

I am currently utilizing Selenium Webdriver to extract content from a webpage. The challenge I'm facing is that the page dynamically loads more content using AJAX as the user scrolls down. While I can programmatically scroll down using JavaScript, I a ...

Issues with Vue enter transitions not functioning as expected

I am currently involved in a project where I need to implement enter and exit animations for some components. When a component enters the screen, it should come from the bottom, and when it leaves, it should go upwards. The intended functionality is that w ...

An issue occurred while attempting to utilize fs.readFileSync

Attempting to change an uploaded image to base 64 format var file = e.target.files[0]; var imageFile = fs.readFileSync(file); var encoded = new Buffer(imageFile).toString('base64'); An error is encountered: TypeError: __W ...

What steps can I take to prompt a ZMQ Router to throw an error when it is occupied?

In my current setup, I have a configuration with REQ -> ROUTER -> [DEALER, DEALER... DEALER]. The REQ acts as a client, the ROUTER serves as a queue, and the DEALER sockets are workers processing data and sending it back to ROUTER for transmission to ...

The jQuery autocomplete feature with typeahead suggestions fails to appear following a successful AJAX request

I am currently using typeahead.js to incorporate tags into my multiple input setup. The tagging function works as expected, however, I am facing an issue where the autocomplete suggestions are not appearing. Is there a solution to fix this problem? Despit ...

Organize your blog content by utilizing post IDs as the designated id attribute

What is the best way to format blog posts and comments in HTML so that I can easily manipulate them later using jQuery/Javascript for tasks like updating, deleting, or making Ajax calls? I am considering using the IDs (primary keys in the database) of the ...

Initially, when fetching data in React, it may return as 'undefined'

I have a function component in React that handles user login. The functionality is such that, based on the username and password entered by the user in the input fields, if the API response is true, it redirects to another page; otherwise, it remains on th ...

What is the purpose of parsing my array if they appear identical in the console?

While working on a D3 component, I came across an interesting question. Why do different arrays require different data treatment even if they all contain the same information? In the first case, I have a 'hardcoded' array that looks like this: ...

Automate the process of triggering the "Organize Imports" command on a VSCode / Typescript project through code

Is there a way to automatically run VSCode's 'Organize Imports' quickfix on every file in a project, similar to how tslint can be run programatically over the entire project? tslint --project tsconfig.json --config tslint.json --fix I want ...

The additional pieces of information transmitted in the state are not being accurately interpreted

I have constants set up that I want to store in the state: const day = "25/02/2020"; const timeStart = "08:00"; const timeEnd = "00:00"; In my Vuex file, I have the following setup: export default new Vuex.Store ({ s ...

Retrieve the most recently added child from the Firebase cloud function

Seeking assistance in retrieving the most recently added child in a cloud function. Below is the code snippet I am using and I'm curious if there is a specific function or query I can utilize to achieve this task without having to iterate through each ...

Adjusting the placement in Draw2D

I'm a newcomer to this library and I'm struggling to figure out how to properly size and position the canvas. If anyone could provide guidance on the best way to do this, I would greatly appreciate it. $(window).load(function () { // se ...