Kashif Hussain
Kashif Hussain

Reputation: 153

remove object from array which have same values in javascript

I'm initializing an array with dynamic objects and result is following

var arr = [
    {id: "", name: "", quantity: 0},
    {id: "", name: "", quantity: 0},
    {id: "", name: "", quantity: 0},
    {id: "", name: "", quantity: 0}
];

now i want to remove any object from this array but not finding proper solution. Can someone please help me how to do it.

Upvotes: 0

Views: 417

Answers (4)

Kashif Hussain
Kashif Hussain

Reputation: 153

Guys thank you so much for your help. I have found solution to this issue, following is what I wanted.

this is my array with initial values set.

var arr = [
    {id: "", name: "", quantity: 0},
    {id: "", name: "", quantity: 0},
    {id: "", name: "", quantity: 0},
    {id: "", name: "", quantity: 0}
];

and I I can remove any object like this:

arr.splice(arr[index], 1);

Upvotes: 1

Abhishek Singh
Abhishek Singh

Reputation: 1671

The solution is that filter your arr Array which has non-empty values like this-:

 var arr = [
    {id: "", name: "", quantity: 0},
    {id: "", name: "", quantity: 0},
    {id: "", name: "", quantity: 0},
    {id: "", name: "", quantity: 0}
];

 arr = arr.filter((obj)=>obj.id!==''); // you can use any field to filter 
 arr = arr.filter((obj)=>obj.id!=='' || obj.name!=='');// multiple fields to filter

Now your arr variable will be updated with new array of objects with non-empty fields

Upvotes: 0

Mahmoud
Mahmoud

Reputation: 936

at the beginning you must know which object you want to delete it (for example the object whose id = x)

then you can use this code

arr = arr.filter(function(e){ return e.id != x });

Upvotes: 1

brk
brk

Reputation: 50291

i want to remove any object from this array but not finding proper solution

You can use splice method, It accepts the index(start) of the to be removed element and also the deleteCount that is number of elements to be removed from the starting index

var arr = [{
    id: "1",
    name: "A",
    quantity: 1
  },
  {
    id: "2",
    name: "B",
    quantity: 2
  },
  {
    id: "3",
    name: "C",
    quantity: 3
  },
  {
    id: "4",
    name: "D",
    quantity: 4
  }
];
arr.splice(1, 1)
console.log(arr)

Upvotes: 1

Related Questions