A quicker method for deleting an element from an array based on its index

Last year, I posted this and now I feel there could be a simpler solution.

I am looking to remove an item from an array based on its index. Even if the array contains duplicate values, I want to be able to remove the item by its index. Here is a common example:

let arr = [1,2,3,2,1] // just a simple array
let x = 1;

// Current approach:
// Find all values equal to 1 and then remove
arr.filter(num => num !== x) //=> [2,3,2]

My desired outcome is if I remove the last element (1), the array should be [1,2,3,2]:

let index = 4; // index of the last "1" in the array
let indexVal = arr.indexOf(4) // 1
let newArray = arr.splice(indexVal, 1) //=> [1,2,3,2]

Fast forward to 2017, almost '18, is there a more concise way (es5/6) to achieve this without the need for any polyfills?

Edit:

Imagine this as a to-do list:

<ul>
  <li>me</li>
  <li>me</li> // click to delete this one
  <li>you</li>
  <li>me</li>
</ul>

To correctly delete that item, I must remove it by the index and not by value

Answer №1

The function callback for Array.filter takes in two arguments: the number and its index, allowing for easy filtering of the array.

let arr = [1,2,3,2,1] 
let x = 4; //let's say we want to remove the element at index 4

let editedArray = arr.filter((num, index) => index !== x) //editedArray = [1,2,3,2]

UPDATE:

The third parameter actually provides the entire array. Shoutout to @Oliver for pointing this out in the comments!

Answer №2

array.removeAtIndex(index);

Alternatively, if you specifically want to delete the last element:

array.removeLast();

Avoid using the indexOf method. It was unnecessary in the first place; it seemed to work because when indexOf doesn't find the element, it returns -1, and splice treats negative indices as counting from the array's end.

Furthermore, keep in mind that splice alters the original array and returns a new array containing the removed elements, so the way you were trying to assign its return value can lead to confusion.

Answer №3

The method that comes to mind is the one utilized frequently in Redux:

const numbers = [1, 2, 3, 2, 1]
const ind = 4 // index of the element to be deleted
const updatedNumbers = [...numbers.slice(0, ind), ...numbers.slice(ind + 1)]
console.log(updatedNumbers) // [1, 2, 3, 2]

Although it may not be the most concise, it is more in line with the current trends and is immutable, which is crucial!

Answer №4

If you're in search for the perfect solution, Ajay's answer might just be what you need. Personally, I prefer a code that is slightly longer but more readable, rewritable, and maintainable. Here's how I would tackle it:

function removeElementByIndex(arr, x) {
    var newArr = [];
    for(var i = 0; i < arr.length; i++) {
        if(i != x) {
            newArr.push(arr[i]);
        }
    }
    return newArr;
}
// Usage
removeElementByIndex([1, 2, 3, 2, 1], 4);// outputs: [1, 2, 3, 2]

As we approach 2018, is there a shorter, more efficient way (using es5/6) to achieve this without any polyfill?

It's quite amusing how many basic functionalities are still lacking. Perhaps we'll have to wait until 2118 or for another programming language to surpass JavaScript (or maybe we already have one - jQuery :P ).

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

Basic looping through a single item to showcase its properties and data

I have an object that looks like this: const people = { men: 4, women: 2, total: 6, participants: { 1: 4, 2: 1, 3: 0 } }; I am looking to display the following result: 1 participants count 4 2 participants count 1 3 participan ...

Is there a way to split each foreach value into distinct variables?

I am looking to assign different variables to foreach values. I have fetched data from an API in JSON format, and then echoed those values using a foreach loop. My goal is to display the echoed value in an input box using JavaScript. I attempted the follow ...

Dealing with asynchronous data using mermaid-js in Angular

Currently, I am engrossed in a project that involves retrieving data from the DB asynchronously and utilizing it to create a sequence diagram using mermaid.js' markdown syntax. Nevertheless, an issue has cropped up where the sequence diagram gets rend ...

Issue with the alphabetical ordering of subpages

My PageSidebar.js component lists child pages alphabetically. https://i.sstatic.net/DZro1.png However, when I navigate to a child page, the alphabetical order is not maintained. https://i.sstatic.net/fRVgO.png I've tried multiple solutions but hav ...

Interactive search tool with multiple fields using HTML and JavaScript

I need help developing a search box for structured data, where I want to implement two types of typeahead searches: one for fields and another for values within those fields. The image below illustrates what I am aiming for. https://i.sstatic.net/MRsJ2.png ...

Working with json, lists, and dictionaries in Python

Apologies for the extensive content, but I wanted to provide all necessary details. I am in the process of extracting specific data points from a JSON file with the following structure: { "count": 394, "status": "ok", "data": [ { ...

Discovering the distinction between arrays of JQuery objects

I have a task that requires the following steps: var elems = $('.lots-of-elements') Next, I need to make an AJAX request and then do this: var moreElems = $('.lots-of-elements') Finally, I am looking to identify only the new element ...

verifying an email address through firebase using the verifyPasswordResetCode method

Currently in the process of setting up firebase authentication. Instead of relying on firebase's default pages for recovery password and email verification, I want to handle these processes directly on my website. To customize the recovery steps: U ...

GAS: What strategies can I implement to optimize the speed of this script?

I have a sheet with multiple rows connected by "";" and I want to expand the strings while preserving the table IDs. ID Column X: Joined Rows 01 a;bcdfh;345;xyw... 02 aqwx;tyuio;345;xyw... 03 wxcv;gth;2364;x89... function expand_j ...

Options for HTML technologies in an application designed for managing enterprise metadata

Challenge We are facing the decision of determining which technologies to adopt as we transition from a rich client Silverlight application to an HTML-based client that can accommodate a metadata driven approach. Situation Our enterprise has been using ...

What is the best way to efficiently input identical data into multiple controllers ($scope) using just one call in AngularJS?

I have a situation where I am using a factory to make a call in two controllers on the same page. However, I want to avoid making an AJAX call twice. I tried using $q.defer(), but it doesn't seem to be working! Here is the code snippet: (function ...

Execute the function once the audio has finished loading

I need help running a function once an audio file has finished downloading. This is my JavaScript code: // https://freesound.org/people/jefftbyrd/sounds/486445/ var audioFile = "https://raw.githubusercontent.com/hitoribot/my-room/master/audio/test/test.m ...

Determine if Param is empty or not within the context of express.js

I am looking to create a table and populate it with all the parameters that are not empty in the parameter list provided below: http://localhost:5002/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="407535732b7008121931190539142 ...

Why is it that GetElements does not provide immediate results upon execution?

Just diving into the world of Javascript for the first time and experimenting with it on Chrome, but running into unexpected results. When I try: document.getElementsByTagName("h1") I anticipate seeing: <h1>tester h1 in body</h1> Instead, wh ...

Creating an array of pointers to 'char' and then retrieving the array

I am trying to create a program that concatenates strings, but I am struggling with returning the string array back to main. char **concatenate(char *strings[], int n) { char buff[200]; char **result[n]; for (int i = 0; i < n; i++) { strcpy(buff, ...

Interactive pop-up messages created with CSS and JavaScript that appear and fade based on the URL query string

I have a referral form on this page that I want people to use repeatedly. After submitting the form, it reloads the page with the query string ?referralsent=true so users can refer more people through the form. However, I also want to show users a confir ...

NodeJs:- Retrieve data from the initial dropdown menu and display it dynamically in the secondary dropdown

Currently, I am working on a dropdown list and facing an issue where the results displayed in the second dropdown need to be filtered based on the selection made in the first dropdown. The EJS code snippet that I am using is: <div class="form-group"& ...

Customizing blockquote styling in QuillJS with a unique class

Currently, I am exploring a method to include a custom class when the user selects the blockquote toolbar button. When the blockquote is clicked, it generates the following element: <blockquote class="ql-align-justify">this is my quoted tex ...

Setting up Laravel Mix Vue.js source maps to display actual component code during debugging

My current setup includes Laravel 5.4 and Vue.js 2.6. I'm facing an issue with viewing the sourceMap of *.vue component files in the console. Here is how I've configured Laravel mix: let mix = require('laravel-mix'); mix.webpackConfig ...

Ways to properly link a webpage using the anchor tag's href attribute

I am currently working with reactjs and bootstrap, and I am trying to display and collapse an unordered list within a list item (nested unordered list). Bootstrap provides a useful collapse feature for this purpose. By using an anchor tag with a data-toggl ...