Removing an array from a nested array using JQuery's key functionalities

I need help removing an array from a multidimensional array if the id matches a given one.

var test_arr = [{"name":"qqq", "city":"it","id":"123456"}, {"name":"ggg", "city":"uk","id":"777456"}];

var result = test_arr.filter(function(v,i) {  
     if (v[0] === '123456'){ test_arr.splice(i,1) } 
}); 

//alert( test_arr[0].id)
alert(result)

http://jsfiddle.net/ofLg0vq5/2/

Can someone guide me on how to achieve this?

Answer №1

The problem with your current approach is that you're not utilizing .filter correctly. The .filter method expects the function provided to return a boolean. If true is returned, the element will be kept in the new array. If it's false, the element gets excluded. Therefore, rather than attempting to remove an element from test_arr using .splice, employ .filter to determine what stays and what goes.

Additionally, note that in your case, v pertains to a specific element (an object) within your test_array. It implies that there's no need to target index 0 of the object; instead, retrieve the current object's id.

var test_arr = [{"name":"qqq", "city":"it","id":"123456"}, {"name":"ggg", "city":"uk","id":"777456"}];

test_arr = test_arr.filter(function(elem) {  
  return elem.id !== '123456'; 
}); 

console.log(test_arr); // [{"name": "ggg", "city": "uk", "id": "777456"}]

If you prefer a more concise solution, you can utilize an arrow function combined with destructuring assignment:

test_arr = test_arr.filter(({id}) => id !== '123456'); // [{"name": "ggg", "city": "uk", "id": "777456"}]

var test_arr = [{"name":"qqq", "city":"it","id":"123456"}, {"name":"ggg", "city":"uk","id":"777456"}];

test_arr = test_arr.filter(({id}) => id !== '123456'); // [{"name": "ggg", "city": "uk", "id": "777456"}]
console.log(test_arr);

Answer №2

@Nick previously provided a solution without using the .splice method. However, if you still prefer using the .splice method for any reason, you can try the code below.

You were checking the id incorrectly in your previous solution. In the following solution, it will remove all objects with the id - 123456

http://jsfiddle.net/u0qshcvf/2/

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

The request for http://localhost:3000/dashboard/js/appclient.js was unsuccessful and returned a 404 (Not Found) error

Among many similar queries, I am puzzled as to why dashboard.html is unable to locate appclient.js, while index.html can successfully find it. The error message received is: GET http://localhost:3000/dashboard/js/appclient.js net::ERR_ABORTED 404 (Not F ...

Switching the event handler in jQuery from click to onload

I have implemented an onclick function that enables an object to go fullscreen when clicked. However, I would like the object to automatically be fullscreen when the page loads, without requiring any user interaction. fbNav.find('ul li.fullscreen&a ...

Seeking assistance with formatting output for OpenCPU and igraph

Here is my adjacency array data: var g = [[10, 2], [15, 0], [18, 3], [19, 6], [20, 8.5], [25, 10], [30, 9], [35, 8], [40, 5], [45, 6], [50, 2.5]] The code I am using in OpenCPU is as follows: ocpu.call("centralization.closeness", {graph: g} ...

Crafting an integrated REST API model with interconnected data

This question revolves around the implementation of a specific scenario rather than a problem I am facing. Let's say we have a User and a Resource, where a User can have multiple Resource but a Resource can have only 1 User. How should API endpoints b ...

Look for and choose various fields from a lengthy JSON object

I am working with a JSON object that contains a large list of offerValue objects. { "Code": 0, "response": "SUCCESS", "offerValue": [ { "id": "111", "name": "ABC", "flag": "V" }, { ...

Is JSON.stringify() the standard object and function in JavaScript for converting objects to JSON?

This is the first time I've encountered this, but it appears to function smoothly even without the use of any JavaScript libraries or frameworks. Is this a built-in feature in JavaScript? If so, where can I locate documentation on this and other less ...

Which is better for Hybrid apps: AngularJS or jQuery Mobile?

Recently I've been pondering over the decision of choosing between Angularjs and jQuery mobile for developing a hybrid app, particularly an eCommerce application. The focus will be on smooth page transitions rather than intense animations, a feature t ...

Can someone please explain the functionality of "next()" in middleware and how it operates?

Currently, I am following a tutorial by Net Ninjas on node.js and attempting to create my own examples to solidify the concepts in my mind. For reference, I refer to the GitHub source code available on their profile. However, I have encountered an issue at ...

How can JavaScript be used to identify duplicate elements within an array?

In a recent interview, I was tasked with finding repetitive elements in an array. While I was able to do so using a for loop, the interviewer requested a more efficient method without using a for loop. I am relatively new to exploring Java script and would ...

"Calculating the average of embedded arrays in MongoDB and storing the result as an

Here is the structure of my documents: { "_id" : "53ce85eda2579da8b40c1f0f", "name" : "Autokino", "tags" : [ "forMen" ], "ratings" : [ { "rating" : 5, "uuid" : "..."}, { "rating" : 4, "uuid" : "..."}, { ...

The number input on my page is stuck and does not update with user interaction

I'm attempting to multiply a user-selected value from the input box by 0.1, but the fetched value is either 0 or remains at the default set value without updating. The chosen value (e.g. 8) by the user doesn't get recognized as the new value. He ...

What is the best way to send a variable using $.post in a JavaScript script?

My jQuery and Javascript code below is responsible for handling the ajax request: else { $.post("http://www.example.com", {email: val}, function(response){ finishAjax('email', response); }); } joi ...

Is there a way to collapse child elements in a hover sidebar using Vuetify?

My project includes a sidebar that opens when I hover over it with the mouse. Everything works fine, but within the sidebar, there is a collapse dropdown menu. When I open this menu and then move the mouse away from the sidebar and back again, the collapse ...

Update my function to be asynchronous by changing async: false to async: true using JQuery and Ajax

I've created a function in a JavaScript class that accesses a PHP file to retrieve information from a database. Although this function works well, I attempted to set the property async: true, and it caused the function to stop working. (I received th ...

Issue with utilizing display: table and overflow: hidden in Internet Explorer and Firefox, functioning properly on Webkit and Blink

JSFiddle : http://jsfiddle.net/h7xvr2t9/2/ I have been experimenting with ways to achieve some effects: Animating a hidden DIV to slide into view from below a visible container Centering text/image on a link to trigger the animation HTML <div clas ...

What is a sleek and stylish method to tally numbers in ascending order?

Is there a way to create a function in JavaScript or PHP that counts smoother than simply adding numbers together? For example: If we have 53 + 39, the result would instantly be 92. But instead of this instant calculation, I want the count to go from 0-1 ...

The operator '$ref' is not valid when utilizing $cond in conjunction with a comparison involving a DBRef

My database has a collection with two columns, 'a' and 'b', that can both point to a user. Currently, I am running an aggregate query to match rows where either 'a' or 'b' has a specific value. I want to use $group t ...

Employing on() for triggering a form submission

I am attempting to attach a submit event handler to a form that may not always be present in the DOM, so I am using .on(): $('body').on("form","submit", function(e){}) However, when checking Firebug, it shows: $("body").on is not a function ...

Why is it possible to initialize a char pointer with a string (array of characters), but not an int pointer with an array of integers?

Why is it possible to initialize a char pointer with a string (array of characters), but not an int pointer with an array of integers? For example, when trying to initialize an int pointer like this: int* a={1,2,3,4,5}; An error message is displayed: ...

retrieving the configuration settings from my customized service

When attempting to access my custom service within its config property in order to inject an HTTP interceptor, I am encountering the following issue: angular .module("common.services") .factory("redirectService", [" ...