The use of array.splice() gives me back the specific item I'm wanting to remove, instead of just the array without

I attempted to eliminate an element from an array by utilizing the indexOf() combined with the splice() method as recommended. However, the outcome is not as expected.

let someArray: string[] = [first, second, third, fourth, fifth, sixth];
let newArray: string[] = someArray.splice(3, 1);

console.log(newArray);

//desired output = [first, second, third, fifth, sixth]

//actual result = [fourth]

This does not align with the information provided in most articles I have come across. Can anyone provide clarification on this issue?

UPDATE I encountered this discrepancy in my code when I received only a single result instead of the expected multiple results, leading me back to this particular point.

Answer №1

When you splice an array, you are modifying it by changing the original array. The element being removed is stored in a new variable called "mine". For example:

var arr = [1, 2, 3, 4];

var mine = arr.splice(1, 1);
console.log(mine);
console.log(arr);

If we print "arr", it will show the original array without index one, and printing "mine" will display [2]. To achieve a different output without mutating the original array, you can iterate through the array and use splice differently like this:

var arr = [1, 2, 3, 4];

var mine = [];

for(var i = 0; i < arr.length; i++) {
    if(i !== 3) {
        mine.push(arr[i]);
    }
}

In this way, the original array remains unchanged as elements are pushed to a new array. If you simply want to mutate the original array, you can directly splice it:

var arr = [1, 2, 3, 4];

arr.splice(3, 1);
console.log(arr);

It's advisable not to mutate arrays outside of functions. Instead, return a value from the function and store it in a new variable:

var arr = [1, 2, 3, 4];


function deleteIndex(ar, i) {
    var a = [];
    ar.forEach(function(elt, index) {
        if(index === i) {

        }
        else {
            a.push(elt);
        }
    });
    return a;
}

var newArr = deleteIndex(arr, 3);
console.log(newArr);

This approach allows flexible deletion based on any criteria without altering the original array structure. Utilizing functional programming or underscore module functions can also assist in these operations.

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

How to Display a Modal Window Automatically Using Bootstrap.js?

Recently, I've become interested in using the Bootstrap library by Twitter for my simple web page. My goal is to have a modal window automatically display after the page loads. If anyone has any tips on how to achieve this, I would greatly appreciate ...

Display an indicator during the file upload process

Is it possible to display an upload indicator using ng-file-upload while the file is being uploaded? I have checked the documentation but couldn't find a solution. Perhaps there is another way to achieve this? ...

retrieving the html select element located within a table td

My code snippet consists of the following HTML elements: <table> <tr> <td><select name="day"> </select></td> <td><select name="time"> </select></td> &l ...

Required file missing in React application unable to locate

I have a project organized in the following way: - my-app - src - some files - public - index.html - ... When I run npm start, the application functions as expected. Now, I am looking to rename src to application! After renami ...

Implementing src attribute to HTML5 audio tag utilizing angularjs

Currently, I am in the process of creating a music website and facing an issue where I need to pass the name of the file when the user clicks on the music cover image to the HTML5 audio tag. My approach involves playing songs using PHP, but it requires a p ...

Grab a hold of the currently active controller in Angular

Is it possible to access a reference to the current instance of the controller from within its definition? My goal is to use `$compile` to create a modal and have it bound to the same controller that initiated its creation. Below is an example of what I w ...

I found that the Angular checkbox was only allowing me to select one value at a time instead of

Hey there, I am currently working on an angular tickbox where I want to be able to tick multiple values. However, I am facing an issue where only the latest checkbox value is displayed instead of both English and German together. How can I populate data fr ...

To ensure at least one checkbox is selected, retrieve the values from the checkboxes and proceed to store them in a state variable for validation

Our form allows users to submit multiple answers in a checkbox format. I'm utilizing the useState hook to manage the answers and validate the array size to determine if the button should be enabled or disabled. Currently, the issue is that even after ...

How can I alter the background color while performing a transformation in JS/CSS?

I'm currently working on achieving a flipboard effect for some divs, where one side is white and the other is black. Here's what I have so far: setInterval(function () { document.getElementById('test').classList.toggle('flipped& ...

Changing the Speed of CSS3 Transitions Dynamically

As I am working with CSS3 Transitions, my current query pertains to initiating the animation with: -webkit-transform: translate3d(-100%, 0, 0); Is there a method to augment the predetermined speed set using: -webkit-transition: all 10s linear; This tim ...

Exploring the ‘ref’ feature in React alongside Material-UI

In my attempt to access input data through React's "ref" attribute on a TextField in Material-UI, I've encountered some difficulties. It doesn't seem straightforward to achieve this using the 'inputRef' or 'inputProps' me ...

Is there a way to conduct a Mongoose query that excludes or ignores specific strings?

I'm struggling to find a concise title, so please suggest ways to make it clearer. Now, onto my question - I need to query phone numbers in my database, but they are stored in two different formats: with dashes and without. For example: {phone: ' ...

Small-scale vue iterates through elements with v-for but fails to display them

I'm really interested in Petite-vue, but I've been struggling to get even the basic functionalities to work. Unfortunately, there isn't a lot of examples or tutorials available online for petite-vue. Can anyone suggest good resources? Right ...

ES5 enables the extension of classes in React

This ES6 syntax works fine for me: import {Component} from 'react'; class A extends Component {} class B extends A { // I can redeclare some methods here } But how would one implement this using ES5? Like so: var React = require('reac ...

Exploring the depths of a TypeScript interface with unknown levels of complexity

My current challenge involves a recursive function that operates on an object with a generic interface. This function essentially traverses the object and creates a new one with a nearly identical interface, except for the leaf nodes which are transformed ...

What is the best approach to generate and organize 100 random numbers in a program, ensuring they are sorted in ascending order from 1 to 100?

I have successfully implemented the sorting and printout functionality of the program. However, I am now facing a challenge in generating 100 random numbers between 1 and 100, sorting them. I have created an array to store the generated numbers, and I ha ...

Adjusting the zoom level in leaflet.js ImageOverlay will cause the marker

Using ImageOverlay to display an image as a map with Leaflet.js, but encountering issues with marker positions shifting when changing the zoom level. Followed instructions from this tutorial, and you can find a code pen example here. // Code for markers ...

Manipulating values in JavaScript using an onclick event in PHP

I am looking to remove the "http" from the URL part of an input link before sending the data. This is my input code that looks like this when clicked: <input style="outline: none;" type="button" onclick="formatText ('link:url');" class="btn ...

Exporting from Blender as an OBJ file and importing it into Three.js seems to be causing issues with the mesh normals

I exported my model from blender to OBJ format and then imported it into Three.js. The normals for the wheels appear to be facing inward. As for the track, only the mesh is visible and it does not seem to be correctly mapped. Upon reimporting the OBJ fi ...

There appears to be an issue with reading the property 'toLowerCase' of an undefined element, and I'm having trouble identifying the error

The variables I have initialized (globally): var audio; var LANGUAGE; var audioArray; var MEDIAARRAY; var WORDS; var SOUNDARRAY; This specific line is causing the error: var audioId = MEDIAARRAY.audio.lowercase.indexOf(exObject['exerciseGetWordInpu ...