0

I am a beginner. I am trying to remove object "Bil' from 'zubi' (object array). Could anyone guide me?

var zubi=[
{a:1,b:1,c:1},
{a:2,b:2,c:2}
]
var Bil={a:1,b:1,c:1}

// the methods I tried which donot work :(
zubi.splice(zubi.indexOf(Bil),1)
zubi=zubi.filter(d=> d!==Bil)
1
  • @ Zubair, you can use JSON.stringify and filter as shown in the answer. Kindly check Commented Jan 13, 2020 at 13:04

3 Answers 3

2

JavaScript objects cannot be compared with equality operator (==).

You can achieve the comparison using deep-equal library:

var equal = require('deep-equal');

zubi=zubi.filter(d=> equal(d, Bil) === false)

underscore.isEqual does the same, you might use that library if you prefer.

Alternatively, in case you do not want to add dependencies to your project, you can compare each property by yourself, as adviced in another answer.

The code would then be:

zubi=zubi.filter(d=> d.a !== Bil.a && d.b !== Bil.b && d.c !== Bil.c);
Sign up to request clarification or add additional context in comments.

Comments

1

You can use filter and JSON.stringify like shown below, So the output will have the array element without Bil Object.

@Update

This approach can be used if the keys order has not changed. Thanks to mehdi for pointing out this one.

var zubi=[
{a:1,b:1,c:1},
{a:2,b:2,c:2}
]
var Bil={a:1,b:1,c:1}

let output = zubi.filter(o => JSON.stringify(o) !== JSON.stringify(Bil))

console.log(output)

2 Comments

Please note that this method is dangerous, since the order of the keys in the object are not guaranteed in the output from JSON.stringify. Source: Why You Shouldn’t Use JSON.stringify to Compare Objects in JavaScript.
Happy to hear :)
1

Each object is uniquely stored even they have same values means:

{a:1} === {a:1} // false

So, in your second case you can check the properties of the object to filter:

zubi=zubi.filter(d=> d.a !== Bil.a);

var zubi=[
{a:1,b:1,c:1},
{a:2,b:2,c:2}
]
var Bil={a:1,b:1,c:1}

// the methods I tried which donot work :(
zubi=zubi.filter(d=> d.a !== Bil.a)

console.log(zubi);

5 Comments

@ Jai we can use JSON.stringify and check it isn't ?
@DILEEPTHOMAS yes that can be done. just convert it to string and compare both. But isn't that look a bit weird.
currently in your code snippet checking for a single property, assume if this case comes var zubi=[ {a:1,b:1,c:1}, {a:2,b:2,c:2}, {a:1,b:2,c:2}, ] , it will filter and give only one object, that is wrong isn't
That is just an example how to compare. OP might get the idea and can use his logic to implement as per requirements.
@ jai, cool because in this approach if 6 or 7 properties are there then he need to add the conditions and && condition thats why i was asking on it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.