What is the best way to remove every other second and third element from an array?

I am looking to remove every second and third element of an array in Javascript.

The array I am working with is as follows:

var fruits = ["Banana", "yellow", "23", "Orange", "orange", "12", "Apple", "green", "10"];

My goal is to delete every second and third element to achieve the following result:

["Banana", "Orange", "Apple"]

I attempted using a for-loop along with splice like this:

for (var i = 0; fruits.length; i = i+3) {
    fruits.splice(i+1,0);
    fruits.splice(i+2,0);
};

However, this approach gives me an empty array because the elements are being removed while the loop is still running.

Can anyone guide me on how to correctly accomplish this task?

Answer №1

You have the option to take a different perspective and push() the unwanted value into a separate Array for deletion:

var initialFruits = []

for (var i = 0; i < fruits.length; i = i+3) {
    firstFruits.push(fruits[i]);
};

While this method may not be as concise as using splice(), it does enhance readability.

Answer №2

To extract specific elements from an array, you can utilize the filter method:

var extractedElements = [
   "Dog", 
   "brown", 
   "3", 
   "Cat", 
   "black", 
   "7", 
   "Bird", 
   "blue", 
   "5"
].filter(function(_, index) {
    return index % 3 === 0;
})

This will result in:

["Dog", "Cat", "Bird"]

Answer №3

This method has been successful for me.

var fruits = ["Banana", "yellow", "23", "Orange", "orange", "12", "Apple", "green", "10","Pear","something","else"];

for(var i = 0; i < fruits.length; i++) {
    fruits.splice(i+1,2);
}

//fruits = Banana,Orange,Apple,Pear

A more enhanced demonstration can be found here: http://jsfiddle.net/RaRR7/

Answer №4

Consider iterating over the array in a reverse manner

Answer №5

One potential solution could be to create a new array by duplicating the first, fourth, and seventh elements. While this approach may not be optimal in terms of memory efficiency, it should still meet your needs.

Answer №6

To efficiently process the array, it is recommended to iterate through it in reverse order. If the condition i % 2 == 0 || i%3 == 0 is met for an element, you can remove that specific element using the splice method.

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

increase the pointer of the float array

I need to shift the float array ptr 256 units from the beginning, which is equivalent to moving it by (256 * 4 bytes) for floats. However, I am encountering a compile time error. long new_capture_length = 4096; long step_size = 256; float data[new_capture ...

Compatible with pure vanilla JavaScript, but not jQuery

I am currently facing an issue with attaching VKI (Virtual Keyboard Interface) to an element that is dynamically added to the DOM using JavaScript. The scenario involves a table with initially only one row, along with "Add Row" and "Delete Row" functionali ...

A Step-by-Step Guide to Successfully Clicking on a Checkbox Using Selenium and Python

Hello everyone, I'm facing an issue with clicking a checkbox. Here is the code for the checkbox: <label class="has-checkbox terms"><input name="order[terms]" type="hidden" value="0" /><input class="checkbox" type="checkbox" value=" ...

The step-by-step guide on displaying API choices in an Autocomplete feature and keeping them up

Having trouble with updating autocomplete options. An error message pops up in the console log when I try to deselect a tag or select a new one: MUI: The value provided to Autocomplete is invalid. None of the options match with [{"catName":{&qu ...

I'm confused as to why this is occurring even though the codes appear to be identical

this.state = { lat: null }; window.navigator.geolocation.getCurrentPosition( pos=>{ this.setState({lat:pos.coords.latitude}); }, err=>{ console.log(err); } ); There seems to be an issue where using setState inside a ...

Automated Form Submission: A Guide to Automatically Sending the Form After Captcha Verification

I'm looking to incorporate ReCaptcha into my website in order to display additional data. My goal is to have the form automatically submitted once the ReCaptcha has been completed, eliminating the need for an extra submit button. However, I've en ...

What is the correct way to dynamically switch between RTL and LTR in React with Material UI?

I recently learned that in order to support right-to-left (RTL) languages with Material UI, you need to follow these steps. I have a select input that allows users to switch between languages, changing the overall direction of the app. The core of my appl ...

React state object iteration doesn't produce any visible output

Trying to dynamically showcase checkboxes with starting values from the state using Material-UI for UI components. tagState: { All: true, Pizza: false, Breakfast: false, Chicken: false } Utilized Object entries and forEach to generate checkbox ...

Variations in the module pattern in JavaScript

Can someone help me understand the differences in these methods of creating a javascript "module"? I'm just looking for some clarification. A) var foo = function() { var bar = function() { console.log('test'); }; retur ...

How can I make <p> elements change color when scrolling?

My Goal I aim to bring attention to the <p> element as the user scrolls on the page. Initially, the opacity is set to 0.3, but I want it to change to 1 gradually as the user scrolls down. My Attempt window.onscroll = function {scrHL}; fu ...

Tutorial on how to update a specific value in an array of objects using setState on click event

I need to toggle the active class on click, setting it to a local state and changing all other objects in the state to inactive. const [jobType, setJobType] = useState([ { "class": "active", "type& ...

There seems to be an issue with $(window).scrollTop() not functioning properly in Safari

While it works smoothly on Firefox and Chrome, there seems to be an issue with Safari. Here is the code snippet: function founders() { var scrollPos = $(window).scrollTop(); if (scrollPos == 900) { $(function() { $(".first_fall").f ...

Making sure Angular picks up on $scope changes

Currently, I am in the process of developing my inaugural AngularJS application and am faced with the challenge of a directive not updating its view when there are changes to the array received from the service. Below is the structure of my directive: an ...

What is the best way to generate a complete PDF of a webpage using pdfmake?

I'm currently developing a web application and facing the task of converting an HTML page, which contains multiple tables and datatables, to a PDF format. To achieve this, I've chosen to utilize the library pdfmake. Below is the script that I ha ...

Change the value in Vue through a single action (swapping out buttons)

I created a custom component that allows users to add points only once by clicking a button. I want to add an undo option to decrease the point value by 1 after it has been added. When a point is added, I'd like the button to change color to red and d ...

Efficiently uploading images with AJAX when submitting a form

I am attempting to upload an image along with other variables in a form submission, and then execute my PHP code to store the image in the user's profile_picture table. I want the image upload to be integrated within the same form used for saving dat ...

Disabling scrolling on body while scrolling a superimposed element

I am working on creating a dynamic image gallery for browsers that support Javascript. The gallery consists of thumbnails that lead to full-size photos displayed in a table layout, complete with navigation links and captions. This table is centered using f ...

Using checkboxes to select all in AngularJS

Recently, I started working with Angularjs and came across some legacy code. I am trying to figure out a way to select all checkboxes once the parent checkbox is selected. Here is the parent checkbox: <div class="form-group"> <label for="test ...

Transforming data from a singular object into an array containing multiple objects with key-value pairs

Looking for assistance with converting data from a single object in JSON format to another format. Here is the initial data: var originalData = { "1": "alpha", "2": "beta", "3": "ceta" } The desired format is as follows: var convertedData = ...

What is the best way to convert the results of a Get-ADComputer PowerShell query into a JSON format that includes the IP address and a parent object such as

After running the following ps1 script: Import-Module ActiveDirectory Get-ADComputer -Filter "OperatingSystem -Like '*Windows Server*' -and Enabled -eq 'True'" | Select-Object Name, DNSHostName | ConvertTo-Json | Out-File &quo ...