"Surprising outcomes when using the splice method on an array

Exploring the functionalities of Array.splice().

deleteCount: A whole number indicating the quantity of old array elements to eliminate.

Understood. It seems clear. I aim to extract the final 4 items in the array. I trust that refers to elements?

arr.splice(<start>, deleteCount<how-many-to-remove>):


// {0 - 8} is a demo of object positioning
let obArr = [{0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}]

// Begin from the end and eliminate four items:
obArr.splice(-1, 4)

console.log(obArr) // not the outcome as anticipated.

console.log(obArr) // expected output: [{0}, {1}, {2}, {3}]

Answer №1

Your approach attempts to remove four values beyond the last item in the array. However, there aren't enough values after the last item to remove four. To successfully remove four values from the end of the array, you should start from an earlier index:

let myArray = [0, 1, 2, 3, 4, 5, 6, 7]

// Start from the 4th last and remove four elements:
myArray.splice(-4, 4)

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

Discovering package utilities with npm commands

When integrating a package into my code, such as: import { Text, View, StyleSheet } from "react-native"; How can I discover the full range of utility functions like Text, View, etc. that are available in the react-native package? Is there an n ...

Identifying the presence of a CSS class in order to add styling to a different element

Looking for help with CSS: /* targeting laptops */ @media only screen and (pointer:fine) and (max-device-height: 620px) { #root:has(.projects) ~ body { overflow: auto; /* allow scrolling */ } } My desired outcome is to set overflow: auto o ...

Having trouble getting the "If paused" feature to function properly in videojs

When my video is paused, I want to display an overlay on top of it. I found the following piece of code in the documentation: var isPaused = myPlayer.paused(); var isPlaying = !myPlayer.paused(); So, I tried implementing it like this: var isPaused = m ...

Pressing the submit button within a form in Ionic2 triggers the Ion-Input onSubmit event

In my form, there is an ion-button and an ion-input included. The ion-button is not meant for submitting the form. When I try to edit a value in the input field and press "ok", I expect the keyboard to hide. However, the ion-button reacts to this event an ...

The JSON data lacks compatibility with the usage of track by functionality

I am working on a project that involves three connected select menus. The first one displays series names, the second one displays chapter numbers belonging to the series selected in the first menu, and the third one displays page numbers belonging to t ...

Tips for efficiently updating state in React.js dynamically?

Is there a way to dynamically update the state of CurrentIndex whenever a user is selected? Currently, it is hardcoded to 0 but I would like to change that. I need the currentIndex to be updated whenever a user from the list is clicked. The SidePan ...

Ensure that the Observable is properly declared for the item list

.html // based on the error message, the issue seems to be in the HTML code <ion-card *ngFor="let invitedEvent of invitedEvents"> <ion-card-content> <img [src]="eventPhotoUrl$[invitedEvent.id] | async"> </ion ...

Stop ajax request when select2 is clicked

Is there a way to change the ajax call behavior in select2 drop down items so that it only retrieves data when I start typing in the search box, and not on click of the element? Your guidance on this issue would be highly appreciated. $("#ddlItems").sel ...

substitute bullet point list item with new element

Assuming I have a list: <ul class="ul-1"> <li class="li-1">xx -1</li> <li class="li-2">xx -2</li> <li class="li-3">xx -3</li> </ul> Then I store it as: var list = $('.ul-1').html(); In ...

Using Vue 3's emit in place of v-model

I am facing a challenge with integrating a custom dropdown select component. The idea is to use v-model to retrieve data from the parent component, but I am unsure how to pass that through an emit. Can anyone clarify this for me? Here is my parent compone ...

Which takes precedence: the end of the script tag or the backtick?

Currently, I am working on developing a page builder widget. My goal is to save the entirety of the HTML code for the edited page to both local storage and a database. The PHP script will load the saved HTML from the database, while JavaScript will handle ...

How can I retrieve the updated input value once a specific key has been pressed in the prototype?

After a customer presses any key, I would like to check an email. Below is the code I am using: document.observe("dom:loaded", function() { $('billing:email').observe('keypress', function(event){ console.log(event.element(). ...

Expanding the width of CSS dropdown menus according to their content

When attempting to create a dynamic dropdown menu, I encountered an issue where the values were skewed in Internet Explorer if they exceeded the width of the dropdown. To fix this problem, I added select:hover{width:auto;position:absolute}. However, now th ...

The HTML element cannot be set within page.evaluate in Node.js Puppeteer

I've run into an issue while using node.js puppeteer, specifically with the page.evaluate method. I'm experiencing difficulties with this part of my code: console.log(response); //This line is valid as it prints a regular string awa ...

Pass information from Vue JS v-for to a button when it is clicked

Just started learning Vue JS and encountered a small issue I'm currently looping through an array with a button inside the div I'm iterating over The goal is to grab the data of the selected item after clicking on the button For example, suppo ...

Prevent Android WebView from attempting to fetch or capture resources such as CSS when using loadData() method

Context To many, this situation might appear to be repetitive. However, I assure you that it is not. My objective is to import html data into a WebView, while being able to intercept user hyperlink requests. During this process, I came across this helpfu ...

One way to transfer data from a Vue table component to another Vue table component is by including an edit button on each row in the table. This allows

When working with two table components, one fetching records using axios and the other needing to get records after clicking on the edit button in the parent component, I encountered issues. Despite attempting Vue's parent-to-child component communica ...

Retrieve the chosen identification from a dropdown menu (select box) with jQuery

I've been on a quest to find a solution for extracting the id from a selected option in a dropdown list. After extensive research, I stumbled upon this helpful resource: Get selected text from a drop-down list (select box) using jQuery I attempted t ...

How can one determine the most accurate box-shadow values?

I am trying to extract the precise box-shadow parameters from a CSS style rule generated by the server. My main focus is determining whether the element actually displays a visible shadow or not. There are instances where the shadow rule is set as somethi ...

Save Scope in JSON format

Currently, I am developing a web application that dynamically displays specific prompts based on the field in focus. There are several different texts stored as scripts that I want to showcase at these different points. My goal is to incorporate scope dat ...