JavaScript remove element from array if element includes specific string

I have a collection of objects that share this structure

[{ id: "11", name: "Car", symbol: "CA" }
,{ id: "13", name: "Cycle", symbol: "CY" }
,{ id: "15", name: "Train", symbol: "TA" }
,{ id: "3", name: "Ufo", symbol: "UF" }]

Suppose I have the string Car, how can I search through the array of objects to identify which object, if any, contains that specific string in the name field and then remove that object from the array?

This is my current progress (Which is essentially nothing as I am unsure how to proceed)

function remove_obj_from_array_of_objs(str, array_of_objs){

}

Answer №1

To achieve this, you can utilize the filter() and includes() methods.

const information = [{ id: "11", name: "Car", symbol: "CA" },{ id: "13", name: "Cycle", symbol: "CY" },{ id: "15", name: "Train", symbol: "TA" },{ id: "3", name: "Ufo", symbol: "UF" }]

const outcome = information.filter(({name}) => !name.includes('Car'))
console.log(outcome)

Answer №2

Utilize Array's filter() method in this way:

var vehicleArr = [{ id: "11", name: "Car", symbol: "CA" }
,{ id: "13", name: "Cycle", symbol: "CY" }
,{ id: "15", name: "Train", symbol: "TA" }
,{ id: "3", name: "Ufo", symbol: "UF" }];

var notIncludesCar = vehicleArr.filter(item => !item.name.includes("Car"));

console.log(notIncludesCar);

Answer №3

Utilize Array.filter in order to selectively remove elements from an array based on a specified condition.

_arr.filter( el => el.name!==_str);

var information = [{ id: "11", name: "Car", symbol: "CA" }
,{ id: "13", name: "Cycle", symbol: "CY" }
,{ id: "15", name: "Train", symbol: "TA" }
,{ id: "3", name: "Ufo", symbol: "UF" }]

function eliminate_array_element(_str, _arr){
  return  _arr.filter( el => el.name!==_str);
}

var response = eliminate_array_element("Car", information);
console.log(response);

Answer №4

To remove an item from an array of objects, start by iterating through the array and checking if the Key value matches your Search String. If a match is found, delete the object at that index from the array:

function removeFromArrayOfObjects(searchString, arrayOfObjects){
    for (var i=0; i < arrayOfObjects.length; i++) {
        if (arrayOfObjects[i].name === searchString) {
            arrayOfObjects.splice(i, 1);
        }
    }
}

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

Struggling to display the array after adding a new item with the push method

Seeking assistance in JavaScript as a newcomer. I have written some code to print an array once a new item is added, but unfortunately, it's not displaying the array. I am puzzled as there are no errors showing up in the console either. In my code, I ...

Move files in Node.js without removing the original source directory

Currently, I am facing an issue while attempting to transfer files from one directory to another using the mv module. The problem arises when the files are successfully moved, but the source directory is automatically deleted. My intention is for only the ...

Simultaneous fading and displaying of the navbar

Currently, I'm in the process of constructing a navigation bar using Bootstrap v4 and have encountered an issue with the collapsing animation in responsive view. Upon inspection of the specific navigation bar, I noticed that the classes (.in and .s ...

Issue with adding events using .on() to dynamically added items in datatables when using ajax based fnDraw()

Whenever the checkbox is selected, a datatable retrieves fresh data using ajax and fnDraw(). Unfortunately, the .on() event is failing to add the event properly. $("#reviewcheck").click(function() { reviewTable.fnDraw(); }); $(".review tbody td img").o ...

Problem with IE8 - jQuery modifying the navigation HTML when the page is resized

I am facing an issue with responsive navigation not working properly in IE8. The navigation disappears when the window is resized, and I want to prevent this from happening. In my HTML code, I have assigned a class of "lt-ie9" for IE8 compatibility. Coul ...

PHP function to determine if an array is a subset of another array

Let's consider the following: $hold = array(1, 1, 4); // this will return true $allArr = array(1, 1, 3, 4, 5); $containsHold = count(array_intersect($hold, $allArr)) == count($hold); When $containsHold is true, it is correct. Now, let's look at ...

Variable fails to be assigned to Element

Having trouble updating the innerHTML attribute for both elements with ids containDiv and status. For some reason, it only changes containDiv but not status. The console shows an error "Cannot set property innerHTML of undefined", indicating that the eleme ...

How can we easily simulate a fetch request designed to only work in the browser using jest?

When testing a function that makes a fetch call, and knowing that all the fetch calls in the project are designed to only run in the browser, do I still need to install a package on node and import it to be able to mock that fetch call? In a simple scenar ...

I encountered the following error: Failed to parse due to the module '@babel/preset-react' being missing

Encountering a parsing error: Module '@babel/preset-react' cannot be found. Upon creating schema.js, tweetSchema.js, userSchema.js, issues arose with import, export, and export from all three files showing red lines. schema.js: import createSche ...

Encountering the ECONNREFUSED 127.0.0.1:3306 error message while trying to launch my node.js application

After launching my node.js application, I encountered the following error message: SequelizeConnectionRefusedError: connect ECONNREFUSED 127.0.0.1:3306 This is what I was trying to do: - create a user: CREATE USER 'main'@'localhost' ...

After installing SDK 34 in Expo, the error message "ExpoNativeModulesProxy native module is not available in NativeModules" is appearing

After updating my react native Expo app to Expo sdk 34, I encountered an error message: The "ExpoNativeModulesProxy" native module is not exported through NativeModules; verify that expo-react-native-adapter's native code is linked properly. Followin ...

Bug with FullPage scrollOverflow sections when scrolling with iScroll's scrollTo() function

I've encountered an issue while using FullPage with scrollOverflow: true. I need to scroll to a specific position in a scrollable section. The problem arises from the fact that FullPage utilizes a modified version of the iScroll plugin for these overf ...

AngularJS ng-hide in UI Bootstrap Alert causing unnecessary space occupation

Utilizing a simple UI Bootstrap alert to display error messages and more, I keep it hidden below a header at the top of my page by default. By using scope variables, I can customize the color and text and utilize ng-hide for hiding. Here's the alert H ...

Creating a Distinct Interior Array Separate from the Exterior

I'm currently working on a project that involves creating a 2D array. I want the interior elements of this array to be black while the exterior elements should be white. However, my 2D array doesn't seem to be forming correctly - it looks more li ...

What is the functionality of array equals useState declarations in JavaScript?

Within ReactJS functional components, the following line enables the creation of: A variable to keep track of the current count A method to update the state when invoked Here's an example in JavaScript: let [count, setCount] = useState([]); Can you ...

Switch back and forth between two tabs positioned vertically on a webpage without affecting any other elements of the page

I've been tasked with creating two toggle tabs/buttons in a single column on a website where visitors can switch between them without affecting the page's other elements. The goal is to emulate the style of the Personal and Business tabs found on ...

The function XmlHttpRequest getResponseHeaders() is not providing a complete list of all headers

Has anyone encountered the issue where jQuery's xhr method, getAllResponseHeaders, only displays the "Content-Type" header when trying to retrieve response headers from an ajax request? Below are the response headers: Access-Control-Allow-Credentia ...

The new URL identifier is malfunctioning, as well as the local storage cache in Internet Explorer

I'm experiencing an issue with the new URL method ('id') in Internet Explorer. Below is the code snippet that I am using: $("#content .left").hide(); $('#'+activeTab).show(); $('#side-menu-parent li a').click(f ...

The unrevealed node that is requesting the module is leading to an undefined outcome

I'm facing an issue where I need to import var server = require('../../index.js'); in my foo-dao.js file. This is necessary for accessing a hapi server plugin without passing it through the hapi request object from controller to dao. The pr ...

How can I troubleshoot jQuery not functioning in iOS even though it works on Safari?

Trying to implement jQuery on a website using xCode simulator for testing, but experiencing issues. Works fine on Safari webkit though. Click here to view the site. I would appreciate finding out what's causing the problem, as well as advice on how t ...