JavaScript: Eliminate a specific element and retrieve the modified array

Is there a way to remove only one instance of an item from an array, even if there are multiple duplicates of that item? For example:

let array = ["abc", "def", "ghi", "def"];
const toRemove = "def";

I attempted to find the index and splice the array, but it ended up deleting the item completely.

const index = array.indexOf(toRemove);
console.log(array.splice(index,1)); //["def"]

Is there an alternative approach to achieve the desired result, where the remaining array is [ "abc", "ghi", "def" ]?

Answer №1

You're so close to the solution. Using the splice() method will change the original array and give back an array containing the altered value(s). Remember to provide both the start and deleteCount arguments when using this method. Once you've done that, simply refer to your original array like this:

let array = ["abc", "def", "ghi", "def"];
const toRemove = "def";
const removed = array.splice(array.indexOf(toRemove), 1) // By passing deleteCount as 1, only that element is removed
console.log(removed)
console.log(array);

For more information, visit https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

Answer №2

The splice() function is used to add or remove elements from an array, while also returning the removed element(s).

It is important to note that this function permanently modifies the original array.

let myArray = ["apple", "banana", "cherry", "banana"];
const itemToRemove = "banana";


const position = myArray.indexOf(itemToRemove);
if (position > -1) {
  console.log(myArray.splice(position, 1));
  console.log(myArray);
}

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

Is there a way to add an entire array of child nodes to a parent node in a single operation using JavaScript?

Is there a quick way in JavaScript to attach an array of child nodes to a parent node all at once? I'm looking for a method that will avoid triggering unnecessary repaints. So far, I attempted using parent.appendChild(arrayOfNodes), but it resulted ...

Is there a way to incorporate locales in calculations involving percentages?

Given the number 4030.146852312 I want to retrieve the four decimal places from this number, resulting in: 4030.1468 Furthermore, I need to format this number according to the specified locale. For example: 4.030,1468 What is the best way to achieve thi ...

Download CSV file directly in Internet Explorer 10 by choosing to open the file instead of saving it on your device

On my server, I have a link available to download a file: <a id="downloadCSVFile" runat="server" href="javascript:void(0)" onclick="parent.document.location = 'CSVFile.csv';">Download</a> I attempted this method as well: <a id=" ...

The property fails to reflect changes in state

I am currently developing an application that requires fetching data asynchronously and preserving the state in the parent component while also passing the data reference to children components. I encountered an issue where the props do not update when the ...

Run a PHP script on the current page upon choosing an option from a dropdown list with the help of Ajax or JavaScript

I'm currently working on a MySQL query that needs to be executed when a user selects options from multiple dropdown lists. What I am looking for is the ability to automatically run a query related to the selected dropdown list option using AJAX/JavaS ...

Sort slider items using Show/Hide feature in bxSlider

I am using a bxslider on my website with specific settings: $('#carousel').bxSlider({ slideWidth: 146, minSlides: 2, maxSlides: 6, speed:500, adaptiveHeight: true, moveSlides:3, infiniteLoop : false, hideContr ...

What is the integration between redux and next.js like?

I am currently trying to integrate Redux into an existing Next.js project, but I am struggling to grasp how the store functions server-side. I came across this example that I am following: https://github.com/vercel/next.js/blob/canary/examples/with-redux ...

Having trouble with the locality function in Google Places v3 API autocomplete?

After successfully using the code below for about a week, I returned to work on it and found that it was no longer functioning properly. My goal is to only display localities. According to Google's documentation, "locality" is the correct option for a ...

Difficulty with xPages repeat control and pager functionality

While navigating, the pager is resetting to position #1. It appears that the page is getting refreshed at some point, causing the pager to reset. I'm having trouble identifying the issue. Have you tried working with the large view? Does it load all vi ...

Injecting resolve into Angular controller and encountering undefined value in logging operation

My setup involves the following: .state('posts', { url: '/posts/{id}', templateUrl: 'posts.html', controller: 'postsController as postsCtrl', resolve: { post: getSinglePostWrapper ...

Receive alerts in Swift from WKWebView when a particular screen is displayed in HTML

Check out this sample HTML file I have. I'm currently using the WKWebView to display this HTML. My goal is to receive a notification in our Swift code when the user finishes the game and the "high score" screen appears, so we can dismiss the view and ...

ESLint flags a misuse of promises in my code that I believe is acceptable

This symbol table implementation includes a method that needs some adjustments: public getAllSymbols(type?: typeof Symbol, localOnly = false): Promise<Set<Symbol>> { const promise = super.getAllSymbols(type ?? Symbol, localOnly); ...

Reactjs throwing an Unsupported Media Type error with code 415

I am currently working on implementing a delete function to remove banner images. Here is the code snippet for my delete function: const [del, setDel] = useState([]); const DeleteBanner = async (banner) => { setDel(banner); ...

Retrieving values from nested JSON arrays in PostgreSQL is crucial for accessing all the data within

I am looking to retrieve all the app_index values from the abc array using a raw query. I am working with a PostgreSQL 10.9 database. So far, I have been able to extract up to the abc key successfully by passing the index number of the array. However, my g ...

Troubleshooting Problems with Wordpress Shortcode Arrays

Here is an example of how a shortcode appears: [posts3col ids="249, 318, 93" category="Events"] Below is the code related to the shortcode: add_shortcode('posts3col', 'posts_func'); function posts_func($atts){ extract(shortcode_a ...

Encountering a 403 error while trying to deploy a Node.js application on Heroku

Yesterday, I encountered an issue while trying to access a Node.js application on Heroku. The error message from the Chrome console was: Refused to load the image 'https://browser-rpg-app.herokuapp.com/favicon.ico' due to Content Security Policy ...

Transfer the values from identical textboxes to jQuery, and subsequently to a PHP page for saving them to a database

Here is a list of textboxes that I have: ` <table id="div1" style="width:100%;"> <tr> <td> <label>Question Text</label> </td> <td colspan="5"> ...

What is the best way to eliminate the first even number from a string?

My task involves working with a string containing only numbers. For example: let inputString = "1234"; The Challenge I need to create a function that will return the string excluding the first even number, if one exists. Example Output: " ...

Indexing text fields for MongoDB collection that have been populated

Currently, I am in the process of learning how to use indexing with Mongoose/MongoDB and I am facing an issue that I can't seem to resolve. This is the schema I am working with: const timeSchema = new mongoose.Schema({ actionId:{ type:St ...

The JavaScript popup is not functioning properly when using a comparison operator

There are 5 links with mini preview photos and URLs. Out of the 3 links, two are considered good while the other two are not. Clicking on a good link takes me to a new page, but clicking on an error link changes the href attribute to addressError, triggeri ...