What causes splice to function properly with a for loop but not with map in JavaScript?

Consider the following 2D array:

var fruits = [["Banana", "Orange", "Apple", "Pear"],
["Banana", "Orange", "Apple", "Pear"],
["Banana", "Orange", "Apple", "Pear"],
["Banana", "Orange", "Apple", "Pear"]];

What is the reason for the discrepancy in results between using map and a for loop?

var newArrayMap = fruits.map(f => f.splice(1,2));
console.log(newArray);


[["Orange", "Apple"], ["Orange", "Apple"], ["Orange", "Apple"], ["Orange", "Apple"]]
for (var i = fruits.length - 1; i >= 0; i--){
        fruits[i].splice(1,2);
    }
console.log(fruits);

[["Banana", "Pear"], ["Banana", "Pear"], ["Banana", "Pear"], ["Banana", "Pear"]]

Answer №1

Array#splice provides a way to delete elements from an array and returns the deleted elements.

When using the first loop with map, it captures the result of the splice operation.

However, in the second loop utilizing for, the returned value of splice is not utilized. The main benefit of using splice is that it modifies the original array, removing unwanted elements.

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

What is the best way to arrange an array to display country data based on Covid cases in descending order rather than alphabetical order?

This particular code snippet retrieves Covid19 statistics data using an API. Currently, it displays the data for covid cases of all countries in Alphabetical order. However, I am looking to present the data in descending order, meaning that the country wit ...

Exploring the realm of JavaScript and finding the perfect spot

Looking to learn more about locating elements and using javascript effectively. For example, when a user clicks on an element, I want to display a menu right below it. I also need to consider scenarios where the element is located at the edge of the page ...

Unable to connect to Alpine store from an external source due to a typescript error

Here is how I have configured my Alpine store: Alpine.store( 'state', ({ qr: '' })) Now, I am attempting to update it from an external source as follows: Alpine.store( 'state' ).qr = 'test' However, I am encounte ...

Django does not retrieve data using fetch()

I am utilizing the fetch() method to send an ajax request to my server. However, when I use request.POST, it returns an empty QueryDict instead of my actual data which is returned by request.body. Can anyone help me figure out what I'm doing wrong? B ...

Checking File Upload Progress in HTML and PHP

As a newcomer, I've been struggling to find a solution to an issue I'm facing. My concern is regarding a form that is meant to upload a file and send it via email. How can I display the progress status of the file being uploaded? It seems that us ...

Initially, the OWL Carousel image is not displaying correctly due to incorrect sizing

I am currently working with OWL Carousel and have implemented a code that displays one image at a time, with the next image sliding in every 15 seconds. The width is set to occupy 100% of the screen and I have configured the JavaScript accordingly so that ...

Dynamic menu item created using Material UI state management

I am facing a challenge in displaying different menu items based on the gender state. Below are the constant values I am working with. const maleArray = ["A", "B", "C", "D"] const femaleArray = ["E", " ...

Creating a Duplicate of an iframe with jQuery

Hey there, I have a dilemma with two divs. One is for displaying content, and the other is a video player that I want to pause and resume on scroll using jQuery. My goal is to pause the video in the "myplayer" div on scroll and have it resume playing from ...

Strategies for Effectively Managing Null Checks in Your JavaScript Project

When retrieving data from the BE API, it is in the format: { "details": { "address": { "street": "123/4", "city": "Banglore" } } } In our React project, we access this dat ...

The revised document now exceeds 16,777,216 in size

When attempting to add new data to an array using mongoose, I encountered two errors. Here is the code snippet in question: return await db.fileMeta.findOneAndUpdate({ username: username, 'files.fileUID': { $ne: data.fileUID } ...

Tracing a path with a snapping motion using my thumb

Before we begin, let's take a look at the example below. The functionality of this component should mimic that of an input type range. However, I am facing some challenges in calculating the step value and snapping the thumb onto the trail based on t ...

Node.js accepts JSON data sent via XMLHttpRequest

I have successfully implemented a post method using xmlhttprequest: var xhttp = new XMLHttpRequest() xhttp.onreadystatechange = function () { if (this.readyState === 4 && this.status === 200) { console.log('Request finished. Pro ...

Tips for preserving newly add row with the help of jquery and php

Currently, I am attempting to implement a functionality on a Wordpress theme options page that dynamically adds rows using jQuery. Below is the HTML code snippet from the THEME-OPTIONS page <a href="#" title="" class="add-author">Add Author</ ...

Why does the getOwnPropertyDescriptor() method in JavaScript include custom properties that are inherited?

As I delve into the world of JavaScript and Node.js, a question has arisen regarding the Object.getOwnPropertyDescriptor() function. Let's explore the following snippet of code: var rectangle = { width: 10, height: 5, get area() { ...

What could be causing my HTML elements to shift position based on varying screen sizes or zoom levels?

Does anyone else experience their HTML and CSS elements shifting around based on the screen size or zoom level? I have screenshots illustrating this issue. Here is how it currently appears And here is how it's supposed to look ...

Retrieving the value of an ASP.NET Literal in JavaScript

Is there a way to retrieve the value of an ASP.NET Literal control in JavaScript? I attempted the code below but it didn't return any values: var companyName = document.getElementById('litCompanyName').textContent; var companyNumber = docum ...

Tips on converting mysql results to JSON using PHP

mysql database table structure: ID >> Name >> Salary The variable $row_set holds information from the database table. However, when using: json_encode($row_set); The output is in this format: [{"0":"1","ID":"1","1":"x","Name":"x","2":"123 ...

What is the best way to use javascript to input data onto a form?

I am looking for a way to retrieve data from my MySql database and display it on an HTTP form. Specifically, when I type in a text field, I want the name of the person to appear. <html> <head> <script type="text/javascript"> func ...

How do I utilize Ajax to compare the value selected from a drop down menu in a form with entries in my database, and retrieve the corresponding record/row to automatically fill in a form?

I have a drop-down menu where users can select an option. I need to match the selected value with the corresponding record in my database under the "invoiceid" column, and then populate a form with the associated data when a prefill button is clicked. Belo ...

What is the best way to add data to my collection using the main.js file on the server side in a Meteor application

I am a beginner with Meteor and trying to customize the tutorial codes. I have a code that listens for packets on my server-side main.js. Now, I need to store the data printed on the console into my database collection. import { Meteor } from 'meteor/ ...