Deleting an element from a looped array in underscorejs

Here is an example of an array:

var list = [5,10,15,20,25];

This code uses the forEach function in JavaScript to loop through the array:

list.forEach(function(item){
  console.log(item);
});

Now, if you want to remove certain items from the array while looping, for instance let's say you want to remove number 15, how can this be done?

Answer №1

Modifying an array while iterating over it can lead to unexpected results and errors. A better approach is to store the indexes that need to be modified in a separate array, then process them after the iteration is complete. Make sure to loop through this index array in reverse order to avoid dealing with changing indices.

Answer №2

Here are 2 different approaches, but I would suggest going with the first method.

const myArray = [10, 20, 30, 40, 50],
    itemsToRemove = [],
    index;

myArray.forEach((element, idx) => {
    if(element === 'something') {
        itemsToRemove.push(idx);
    }
});

while((index = itemsToRemove.pop()) !== null) {
    myArray.splice(index, 1);
}

// OR
for(index = myArray.length - 1; index >= 0; --index) {
    if(myArray[index] === 'something') {
        myArray.splice(index, 1);
    }
}

Answer №3

To achieve this with underscores, you can follow these steps:

let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

let evenNumbers = _.filter(numbers, function(num){

    // Perform a task for each number - in this case, just logging the number
    console.log(num);

    // Only select even numbers
    return num % 2 == 0;

});

// Display the filtered list of even numbers
_.each(evenNumbers, function(num){
    console.log(num);
});

Answer №4

Utilizing Underscore can significantly reduce the amount of code you need to write. This tool is truly a valuable resource.

var list = [10, 20, 30, 40, 50];
list = _.without(list, _.findWhere(list, {
  id: 3
}));
console.log(list);

Answer №5

Below is an efficient method I utilized to solve this issue by utilizing underscore's reject function:

_.each(_.reject(list, function(item) { return item === 10}), function(element){
  console.log(element);
});

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

Eliminate the legend color border

I have successfully implemented the following code and it is functioning properly. However, I am trying to remove the black boundary color legend but am struggling to figure out how to do so. var marker = new kendo.drawing.Path({ fill: { co ...

Transform your traditional sidebar into a sleek icon sidebar with Semantic UI

I am working on customizing the semantic-ui sidebar. My goal is to have it minimize to a labeled icon when the toggle button is clicked. However, I am having trouble with the animation and getting the content to be pulled when I minimize it to the labeled ...

What is the best way to replace multiple strings with bold formatting in JavaScript without losing the previous bolded text?

function boldKeywords(inputString, keywords){ for (var i = 0; i < keywords.length; i++) { var key = keywords[i]; if (key) inputString= inputString.replace(new RegExp(key, 'gi'), '<strong>' + ...

Axios cancel token preemptively cancelling request before it is initiated

Currently, I am working on implementing cancellation of axios calls in my project. After reviewing the axios documentation, it appears to be quite straightforward, which can be found here. To begin, I have defined some variables at the top of my Vue compo ...

"Enhancements in Next.js 13: Optimizing static site generation with improved cache-control and index.txt management

In my setup with Next.js version 13, I have stored my build in a bucket. My goal is to ensure that the user's browser always fetches the latest build of my static site. However, I'm facing an issue where each folder/page on the website has an i ...

Issues encountered when utilizing the each method to retrieve ajax data

Here is the issue I am facing: I am attempting to apply a red border to fields that are empty using the jQuery code below: $("#frmId input, #frmId select, #frmId textarea").each(function(){ if($(this).val() == ""){ $(this).css('borde ...

Encountering Issues with Formatting InnerHtml Text using RegEx

Technology: React.js I have been working on a custom function in JavaScript to highlight specific words within a code block. The function seems to be functioning correctly, but the highlighting isn't staying after the function is completed. Any ideas ...

Reset IntersectionObserverAPI to its initial state when none of the elements are in view

Currently, I am utilizing a React Hook that enables me to observe when an element becomes visible in the viewport. The functionality works smoothly until I encounter the need to 'reset' the state once all elements are hidden (such as when reachin ...

Retrieving information from a Rowdatapacket with expressjs

Is there a way to use a loop to retrieve a single value from each row in RowDataPacket? Currently, my results look like this: [ RowDataPacket { id: 522, number: '111', test: 'testing' }, RowDataPacket { id: 523, number: '112' ...

math symbols in brackets of python array that can be compared

Imagine working with an array like this: numbers = [1,2,3,4,5,6,7] Now, let's take a look at this snippet of code: print(numbers[0<=3]) What is the purpose of this code? How does it function? ...

Submitting form data in Angular is a straightforward process

I'm currently using the ng-flow library to upload images to my server. After a user drags and drops an image, I can successfully retrieve the HTML 5 file image in my controller. However, when trying to download it to the server along with other parame ...

Is the useNavigate() function failing to work consistently?

Currently facing an issue while working on a MERN Web App. When logging in with an existing account, the backend API call returns user properties and a JWT Token. Upon saving it, I use the navigate function to redirect the User to the homepage. Everything ...

Having trouble passing data from router to View with EJS in Express. Despite trying, still encountering ReferenceError message

I encountered an issue when trying to display form errors to the user. I attempted to pass the errors from the router to my view file. Error Message ReferenceError: e:\2016\passport\views\register.ejs:38 36| 37| <div ...

Retrieving Information from MongoDB Collection with Paginated Results in Universal Sorted Sequence

I'm in the process of working on a project that involves a MongoDB collection called words, which holds a variety of words. My objective is to retrieve these words in a paginated manner while ensuring they are globally sorted in lexicographical order. ...

How can I recreate this image in 3D using three.js?

I have a tower image' - but i don't know how to replicate this for3dview using thethree.js` any assistance would be greatly appreciated! Here is the image : This is my attempt : $(function () { "use strict"; var container, scene, cam ...

Is there a way for me to create a clickable link from a specific search result retrieved from a MySQL database using an AJAX

Currently, I am attempting to create an ajax dropdown search form that provides suggestions based on results from a MySQL database. The goal is for the user to be able to click on a suggestion and be redirected to the specific product. The code I am using ...

Choose the text value of the jQuery select menu from the specified column in the table

I need to search through all the select elements in a specific table column with the id "tdcities". I want to compare their ids with the row id and if there is a match, I need to select the text value. Below is the code I am currently using: $("#tdcities ...

The JavaScript Top Slide Down effect is malfunctioning

Every time I press the "More" button, I expect some forms to pop out but nothing happens. Can someone please assist me with this issue? <body> <!--Hero Image--> <div class="hero-image"> <div class="hero ...

Unable to pass value through form submission

Having some trouble displaying data from an API on my HTML page. The function works fine when I run it in the console. <body> <div> <form> <input type="text" id="search" placeholder="Enter person& ...

Determine browser compatibility by evaluating the DOM Level

Can we easily determine which browser versions and above are compatible with a certain DOM level? ...