Removing an item from an array depending on a specific condition and index

I am working with an array structure that looks like this:

[
  {key: 4, data: {…}, qText: {…}},
  {key: 4, data: {…}, qText: {…}, isVisible: false},
  {key: 5, data: {…}, qText: {…}, isVisible: false},
  {key: 4, data: {…}, qText: {…}, isVisible: false}
]

My goal is to remove elements from the array based on two conditions:

  1. If I receive a key value input of 4, then all keys with value 4 should be deleted.

  2. The second scenario involves deleting a specific key and index when certain criteria are met within the nested data. For example, in the given array, if I receive an index of 1 and a key of 4, only that particular element should be removed.

I initially attempted to solve this problem using multiple loops, but it was not very effective. What would be the most efficient approach performance-wise to achieve this? 1) Firstly, I tried to find the keys as shown below:

const deleteKey = this.followUpQues.filter(quest =>
  quest.data.choice.some(y => y.id === item.id)
).map(quest =>
  quest.key
)

2) Next, I attempted to determine the index using the following code:

this.followUpQues.forEach(function(val, index) {
  if (val.data.choice.filter(y => y.id === item.id).length >= 1) {
    keyNumber = val.key;
    valueIndex = index;
  }
})

this.followUpQues.splice(valueIndex + 1, this.followUpQues.length - (valueIndex + 1))

Answer №1

Utilizing the filter() method allows you to generate a new array excluding elements that meet certain criteria.

const array = [
  {key: 4, data: {}, qText: {}},
  {key: 4, data: {}, qText: {}, isVisible: false},
  {key: 5, data: {}, qText: {}, isVisible: false},
  {key: 4, data: {}, qText: {}, isVisible: false}
];

const result = array.filter((obj, index) => !(obj.key == 4 && index > 2));
console.log(result);

If your intention is not to create a new array but to modify the existing one, I recommend using a reverse for loop and the splice() method to eliminate elements. It's crucial to work in reverse order as removing elements can cause shifting. Reversing the loop anticipates the shifting of elements already being accounted for.

const array = [
  {key: 4, data: {}, qText: {}},
  {key: 4, data: {}, qText: {}, isVisible: false},
  {key: 5, data: {}, qText: {}, isVisible: false},
  {key: 4, data: {}, qText: {}, isVisible: false}
];

for (let i = array.length - 1; i > 2; --i) {
  if (array[i].key == 4) array.splice(i, 1);
}

console.log(array);

Answer №2

You can see a functional demo here:

const items = [
  {id: 4, content: {}, textContent: {}},
  {id: 4, content: {}, textContent: {}, display: false},
  {id: 5, content: {}, textContent: {}, display: false},
  {id: 4, content: {}, textContent: {}, display: false}
]

function removeItem(array: any[], id: number, index: number = 0) {
  let currentIndex = 0;
  for (const currentId in Object.keys(array)) {
    if (items[currentId].id === id) {
      if (currentIndex < index) {
        currentIndex++;
      } else {
        delete array[currentId];
      }
    }
  }
}

removeItem(items, 4, 2);

console.log(items);

Please be aware that this modifies the original array. If you wish to get a new array, you must also implement a deep clone method.

Answer №3

To eliminate an element from a list after a specific index, you can execute the slice method and then utilize a predicate function to locate the desired item. Once the item is found, determine its index. If the index is greater than -1, proceed with removing it.

const data = [
  { key: 4, data: '', qText: '' },
  { key: 4, data: '', qText: '', isVisible: false },
  { key: 5, data: '', qText: '', isVisible: false },
  { key: 4, data: 'Delete me!', qText: '', isVisible: false }
];

const remove = (list, predicate, fromIndex = 0) => {
  const found = list.slice(fromIndex).find(item => predicate(item));
  const index = list.indexOf(found);
  if (index > -1) list.splice(index, 1); // Remove
  return list;
}

console.log(remove(data, item => item.key === 4, 2));
.as-console-wrapper { top: 0; max-height: 100% !important; }


Note: It's important to note that due to slicing the list at a given index, using findIndex might not give accurate results as it returns indices based on the sliced array. A possible solution is adjusting for this offset accordingly.

const remove = (list, predicate, fromIndex = 0) => {
  const foundIndex = list.slice(fromIndex).findIndex(item => predicate(item));
  if (foundIndex > -1) list.splice(foundIndex + fromIndex, 1); // Remove
  return list;
}

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

Why is the Twitch api map function returning nothing, while the console log is showing output?

Presently, my Nextjs page is making multiple Twitch API calls successfully and displaying the correct data. However, one of the mapping functions is failing to render anything on the page, even though the console log shows the data. Although I am relativel ...

Using Typescript and React to render `<span>Text</span>` will only display the text content and not the actual HTML element

My function is a simple one that splits a string and places it inside a styled span in the middle. Here's how it works: splitAndApplyStyledContent(content: string, textType: string, separator: string) { const splittedContent = content.split(separat ...

There are two references to an object, but even if one of them is modified, the second reference continues to show the

During my attempts to troubleshoot an issue in a JS plugin, I noticed that one variable was sometimes affecting another and sometimes not. In order to investigate further, I added the following code: var a = $('#w3').data('fileinput'). ...

Prevent certain images from loading by blocking them

I am trying to create an extension that blocks two specific images from loading. Initially, I attempted to achieve this by using the following code in the content.js file: $("#rated-image").remove(); //id of one image $(".blur-mask").remove(); //class of ...

Stop users from refreshing or closing the window while an axios request is being processed

I'm in the process of creating a dynamic Web Application that involves utilizing Axios.get requests. Given that Axios operates asynchronously, my approach includes an async function along with await axios.all: async handleSubmit(){ const ...

Tips for obtaining a slice as an array in Rust?

I'm facing a challenge with an array of unspecified size, as I aim to extract a portion of that array and transform it into a statically sized array: fn pop(barry: &[u8]) -> [u8; 3] { barry[0..3] // expecting array `[u8; 3]`, but getting sl ...

Close any open alerts using Protractor

While using protractor and cucumber, I have encountered an issue where some tests may result in displaying an alert box. In order to handle this, I want to check for the presence of an alert box at the start of each test and close/dismiss it if it exists. ...

Is there a way to use node.js to retrieve a video in mp4 format?

My goal is to allow users to download a video from my AWS S3 bucket in MP4 format: app.get("/download_video", function(req,res) { filename = "s3.xxx.amazon.com/bucketname/folder/video_example.mp4"; // I'm unsure about the next steps }); Whil ...

Managing errors in jQuery's .ajax function

Having some issues with jQuery.ajax() while trying to fetch an html code snippet from table_snippet.html and replacing the element in my html code. The error handler in jQuery.ajax() gets triggered instead of the expected success handler. <!DOCTYPE H ...

Transforming a string that represents an array into an actual array using JavaScript

Currently, I am working on a project that involves the use of MySQL, React, and Express.js. One issue I have encountered is the need to save an array into MySQL. However, there seems to be no direct way to do this, so I had to convert the array into a st ...

leveraging dependency injection to retrieve a function in JavaScript

I'm exploring a way to obtain a function in JavaScript without executing it, but still defining the parameters. My current project involves creating a basic version of Angular's dependency injection system using Node.js. The inject() method is us ...

The sidebar in tailwind css is not displaying a scrollbar as expected

I'm currently working on a project to create a WhatsApp clone using Tailwind CSS in ReactJS. However, I've encountered an issue with the contacts list where it's not showing the scrollbar and instead overflowing the content, leading to the w ...

React - assigning a value to an input using JavaScript does not fire the 'onChange' event

In my React application with version 15.4.2, I am facing an issue where updating the value of a text input field using JavaScript does not trigger the associated onChange event listener. Despite the content being correctly updated, the handler is not being ...

Exploring the foundational element within a JSON structure

I'm trying to retrieve the album names of various artists from a JSON file located at this link. My current approach involves writing the following code: var json = JSON.parse(request.responseText); //parse the string as JSON var str = JSON.stringify ...

The display of temporary headers - Nodemailer - AJAX

I keep receiving a warning in the request header that says: Provisional headers are shown. I'm struggling to identify the root cause of this issue. This warning prevents the readyState from changing and my callbacks on the eventhandler onreadystatecha ...

Using Material-UI in a project without the need for create-react-app

My objective is to utilize Material-UI without relying on create-react-app, as I feel that it abstracts too much and hinders my learning process. Unfortunately, all the instructions I have come across are centered around create-react-app. I am aiming to s ...

BlurDataURL for Data URLs in Next.js

NextJS 11 brings the exciting feature of using the Image component with a blur placeholder. To utilize this with dynamic images, we need to make use of the blurDataURL, which is a Data URL. I am interested in taking my original image and resizing it to a ...

Ensuring the safety of generic types in Typescript

Typescript is known for its structured typing, which is a result of the dynamic nature of Javascript. This means that features like generics are not the same as in other languages with nominal type systems. So, how can we enforce type safety with generics, ...

When the 'Show More' button is clicked, one Div will smoothly slide over another Div

I've been struggling for hours to find a way to make one DIV slide over another DIV below it instead of pushing it down. The setup is quite straightforward. I have a script that reveals more text when the 'Show More' button is clicked. Desp ...

Can someone explain how to showcase a collection attribute in Angular?

I am working with a collection of objects called "ELEMENT_DATA". Each object in the collection has an attribute named "Activite", which is also a collection. My goal is to display this attribute in a specific way. Below is my app.component.ts: export cla ...