简体   繁体   中英

Unable to remove a specific Item from array

I have a simple array as

arr=[{"name":"sam","value":"1"},{"name":"ram","value":"2"},{"name":"jam","value":"3"},{"name":"dam","value":"4"}]

I need to remove the first index from this array and it should be of below type

[{"name":"sam","value":"1"},{"name":"jam","value":"3"},{"name":"dam","value":"4"}]

I tried splice as below

arr.splice(1,1)

But it is giving response {"name":"ram","value":"2"}

how to get [{"name":"sam","value":"1"},{"name":"jam","value":"3"},{"name":"dam","value":"4"}]

It might be very simple question but Im stuck here from sometime.can someone plz help

I think you taking the returning value of Array.prototype.splice() .

Array.prototype.splice() returns an array containing the deleted elements.

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place

 arr=[{"name":"sam","value":"1"},{"name":"ram","value":"2"},{"name":"jam","value":"3"},{"name":"dam","value":"4"}] arr.splice(1,1) console.log(arr);

You can compare the difference methods. Be aware if you need change the array or just get a copy to keep with the original one.

Attention : The first array index is 0 , not 1 . The index one is the second element of the array

The splice method return the element removed from array. That's the reason why you've got the second element from array in your test

Doc:https://bytearcher.com/articles/how-to-delete-value-from-array/

In your question you got the second index that is 1 , in order to get the values that was shown, I'll use the index 1 as well.

 //DELETE arr=[{"name":"sam","value":"1"},{"name":"ram","value":"2"},{"name":"jam","value":"3"},{"name":"dam","value":"4"}] delete arr[1]; console.log("using delete",arr) //SPLICE METHOD arr=[{"name":"sam","value":"1"},{"name":"ram","value":"2"},{"name":"jam","value":"3"},{"name":"dam","value":"4"}] let firstElement = arr.splice(1,1) console.log("using splice",arr) console.log("the method splice return the element removed from array",firstElement ) //FILTER METHOD arr=[{"name":"sam","value":"1"},{"name":"ram","value":"2"},{"name":"jam","value":"3"},{"name":"dam","value":"4"}] let copyArr = arr.filter((element, index)=>index.== 1) console:log("extra, using filter (will return a array copy)",copyArr)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM