How to delete an element from an array with UnderscoreJS

Here's a scenario:

var arr = [{id:1,name:'a'},{id:2,name:'b'},{id:3,name:'c'}];

I'm looking to delete the element with id value of 3 from this array. Is there a method to achieve this without using splice? Perhaps utilizing underscore or a similar tool?

Appreciate your help!

Answer №1

If you prefer using plain JavaScript, the solution to removing objects from an array based on object property was already provided in this post: remove objects from array by object property.

Alternatively, if you opt for underscore.js, you can utilize the combination of .findWhere and .without:

var arr = [{
  id: 1,
  name: 'a'
}, {
  id: 2,
  name: 'b'
}, {
  id: 3,
  name: 'c'
}];

// exclude third item
arr = _.without(arr, _.findWhere(arr, {
  id: 3
}));
console.log(arr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

However, if you are creating a new array anyway, consider using _.filter or the native Array.prototype.filter function instead (as demonstrated in the linked question). This will result in a more efficient iteration over the array without potentially double traversal.

To modify the array directly (in-place), use .splice, as discussed in the other question. Underscore does not offer a specific function for this purpose.

Answer №2

If you want to filter an array using Underscore, you can use the .filter method.

var data = [{
      id: 1,
      name: 'apple'
    }, {
      id: 2,
      name: 'banana'
    }, {
      id: 3,
      name: 'carrot'
    }];

    var filteredData = _(data).filter(function(item) {
         return item.id !== 3
    });

An alternate way to achieve the same result is:

var filteredData = data.filter(function(item) {
    return item.id !== 3
});

var filteredData = _.filter(data, function(item) {
    return item.id !== 3
});

View Fiddle

You can also explore the .reject method for similar functionality.

Answer №3

Utilize Underscore's _.reject() method:

list = _.reject(list, function(item){ return item.id === 3; });

Answer №4

For those looking to efficiently remove items from an array, Underscore offers the _without() method as a perfect solution.

This method returns a modified copy of the original array with specified values removed.

_.without(["apple", "banana", "cherry"], "apple");

=> ["banana", "cherry"]

The flexibility of _without() extends to more complex objects as demonstrated below.

var apple = { Name: "Apple", Price: 1.99 };
var banana = { Name: "Banana", Price: 0.79 };
var cherry = { Name: "Cherry", Price: 3.49 };

var fruits = [apple, banana, cherry]

_.without(fruits, banana);

=> [{ Name: "Apple", Price: 1.99 }, { Name: "Cherry", Price: 3.49 }];

If you only have a property value to identify the item for removal, combining _.findWhere and _.without is another effective approach.

Answer №5

When filtering strings with case insensitivity in mind, it's important to be cautious. The _.without() function is case sensitive, so you may want to consider using _.reject() instead. See the example below for how this can be done:

var array = ["example","example1","example2"];

var filteredArray = _.filter(array, function(item) {
    return item.toLowerCase() !== "EXAMPLE".toLowerCase();
});
console.log(filteredArray);
// ["example1", "example2"]

var filteredArray1 = _.without(array,"EXAMPLE");
console.log(filteredArray1);
// ["example", "example1", "example2"]

var filteredArray2 = _.reject(array, function(item){ 
    return item.toLowerCase() === "EXAMPLE".toLowerCase();
});
console.log(filteredArray2);
// ["example1", "example2"]

Answer №6

If you wish to make changes to an array without creating a new copy, you can perform the following operation:

arr.splice(_.findIndex(arr, { id: 3 }), 1);

However, this method assumes that the element will always be present in the array (as it will remove the last element if not found). For a safer approach, consider using the code snippet below:

var index = _.findIndex(arr, { id: 3 });
if (index > -1) {
    arr.splice(index, 1);
}

Answer №7

Here's an alternative method to achieve the same outcome:

_.reject(arr, function(obj) { return obj.id === 3; });

Just a thought

Answer №8

Utilize the power of plain vanilla JavaScript by leveraging Array#filter method in the following way:

var arr = [{id:1,name:'a'},{id:2,name:'b'},{id:3,name:'c'}];

var filteredArr = arr.filter(obj => obj.id != 3);

console.log(filteredArr);

Alternatively, you can opt for Array#reduce and Array#concat methods as shown below:

var arr = [{id:1,name:'a'},{id:2,name:'b'},{id:3,name:'c'}];

var reducedArr = arr.reduce((accumulator, currObj) => {
  return (currObj.id != 3) ? accumulator.concat(currObj) : accumulator;
}, []);

console.log(reducedArr);

PLEASE NOTE:

  • Both of these techniques follow a pure functional approach (i.e. they preserve the original array).
  • No external libraries are necessary with these strategies (Vanilla JavaScript is sufficient).

Answer №9

I experimented with this technique in the past

_.filter(data, d => { return d.name !== 'a' });

Other users have also suggested alternative solutions that may be more effective

Answer №10

Utilizing underscore.js

var data = [{id:1,name:'a'},{id:2,name:'b'},{id:3,name:'c'}];

var newResult = _.reject(data,{id:3});

console.log(newResult);

The output would be :: [{id:1name:'a'},{id:2,name:'c'}]

Answer №11

To filter out specific items from an array, you can utilize the reject method from Underscore. The example below demonstrates how to create a new array without the item that matches a certain condition.

arr = _.reject(arr, function(objArr){ return objArr.id === 3; });

Answer №12

Underscore.js is a library that offers:

_.filter(arr);

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

Updating the jQuery datatable with new data after a page switch or another action

One of the features on my page is a jQuery datatable that I populate with data using the following script: $(document).ready(function () { var dataTable; $(document).on("click", ".myBtnClass", function () { if (dataTable != null) ...

The Clash of Form Action and JavaScript

Can someone help me with this issue? I have a form and a script to trigger an alert message. The code I'm using is working well: <input id="autocomplete" class="input_message" type="text" name="message" autocomplete="off" placeholder="...typ ...

How to sort data in AngularJS by clicking on a column to change the order from ascending to

The code view below is what I am currently working with: <tr ng-repeat="c in clients | orderBy:'code'"> <td>{{c.firstname}} {{c.lastname}}</td> <td>{{c.telephone}}</td> <td>{{c.location}}</td> ...

Having trouble preventing Selenium webdriver from automatically closing the safari browser

Experiencing a strange issue with Safari where it closes the browser immediately after running the code snippet below, while Chrome and Firefox behave as expected. I am using Webdriver with JavaScript for this automation. let driver = await new Build ...

Ways to stop the react-router from causing the page to refresh

Need assistance with React Router issue I'm working on a project in reactJs using react-router-dom v5. I have set up a default route for routing. <Redirect to={"someComponent"}/> The problem is that when I refresh the page, it auto ...

What is the most efficient way to retrieve the current user's ID within Loopback?

Given the instability and deprecation of loopback.getCurrentContext(), what strategies can I use to accurately identify users when they interact with API endpoints? Is it feasible to include the token ID in the request payload for verification purposes? H ...

Using JavaScript to swap between multiple images can be a powerful tool, but sometimes the wrong image

I'm having an issue with duplicating an image swap function. The problem is that the mouseout event is triggering image 3 on each of the three swaps, when I actually want it to trigger only on the last one. Can anyone provide some guidance on how to m ...

The button labeled "issett" is malfunctioning

Hey there, so I've created a registration form using jQuery and PHP that validates user input in real-time as they type. Once all the information is correct, I want to allow the user to submit the form. My plan is to write an if statement that checks ...

The value sent from the ajax call did not reach the PHP file as expected

Here's the code I'm working with: HTML and Javascript: function getValues(){ var filter; $.ajax({ type: "POST", url: "myphpfile.PHP?action=sek", data: "id=1", async: false, suc ...

Having trouble generating a dynamic ref in Vue.js

I am currently working on rendering a list with a sublist nested within it. My goal is to establish a reference to the inner list using a naming convention such as list-{id}. However, I'm encountering difficulties in achieving this desired outcome. B ...

JS/Chrome Extension: Ways to Verify if a User is Currently Logged In

After building a Chrome extension, I am now looking to seamlessly integrate it with my existing PHP-based website. This website allows users to have their own accounts and save their favorite items, similar to a Pinterest platform. My main question is whe ...

JQGrid will automatically conceal any row that contains a false value in a given cell

I'm attempting to conceal a row if a specific cell within it contains the value false. To achieve this, I have experimented with using a formatter in the following manner: $("#list").jqGrid({ //datatype: 'clientSide', ...

Displaying error messages on a form that uses ng-repeat in Angular

I am trying to dynamically generate input fields using ng repeat in Angular, but I am encountering an issue where error messages only appear on the last element. How can I make these error messages apply to each individual element? <form name="setPla ...

Unable to input characters consecutively into the text field because it is being displayed as a distinct function within the component

When attempting to bind a text field using the approach below, I encounter an issue where entering characters in the text field causes the control/focus to shift out of the field after the first character is entered. I then have to click back into the text ...

JavaScript and TypeScript: Best practice for maintaining an Error's origin

Coming from a Java developer background, I am relatively new to JavaScript/TypeScript. Is there a standard approach for handling and preserving the cause of an Error in JavaScript/TypeScript? I aim to obtain a comprehensive stack trace when wrapping an E ...

The props in Vue 3 are not functioning as expected in child components even after being bound correctly, resulting in undefined values in the child component

Exploring the realms of Vue and Laravel, I find myself in new territory. As the parent element, I fetch items from the database successfully. Now, the task at hand is to pass this data to the child component. <template> <div class="todoList ...

Prisma DB is a versatile database that excels in handling m-n

In my database, I have implemented a structure with 3 tables: Member, Characters, and MemberCharacters. Each member can have multiple Characters, and each Character can be used by multiple Members. To handle this many-to-many relationship, I have utilized ...

Using JQuery to make a GET request and receive a JSON response, then selecting particular objects

I am in the process of developing a straightforward web application. The concept involves users inputting a license plate number, which will then connect to an OpenData API based on Socrata that houses information about all registered vehicles in my countr ...

The canDeactivate function in the Angular 2 router can modify the router state even if I choose to cancel an action in the confirmation popup

In my Angular 2 project, I have implemented the canDeactivate method to prevent browser navigation. When a user tries to leave the page, a confirmation popup is displayed. However, if the user chooses to cancel, the router still changes its state even th ...

UI-data contracts: enhancing client-side JSON data validation

I have encountered situations where the JSON data I receive from services and database calls, created by a different team, contains invalid data combinations that lead to unintended errors downstream. For example, in the case below, if the "rowContent" fi ...