2

I have two object array in Js

a = [{"photoId":"1","albumId":"121"},{"photoId":"2","albumId":"131"},{"photoId":"3","albumId":"131"}] ;
b = [{"photoId":"2","albumId":"131"}];

I want to remove b object array entry from the a object array..so the output should be

c = [{"photoId":"1","albumId":"121"},{"photoId":"3","albumId":"131"}];

its easy to achieve in case of array but how to do the same for array object..

2 Answers 2

2

It looks like an object array is more difficult, but is actually the same as a 'normal array'. Just check on its content. You should loop trough the array to check if the objects are the same. Then use the Array.slice() like this:

for (var i = a.length - 1; i >= 0; i--) //always use a reversed loop if you're going to remove something from a loop
{
  if (a[i].photoId == b[0].photoId &&
      a[i].albumId == b[0].albumId) // if the content is the same
  {
     a.splice(i, 1); // remove the item from 'a'
  }
}

BTW the delete-statement makes the item in the array empty, splice removes it completely, so the length of the array becomes smaller.

Note; If you are dealing with references of the same object, you could use this condition:

if (a[i] == b[0])

Ofcourse, if there are more items in 'b', you'll have too build a double loop.

Hope this helps.

Sign up to request clarification or add additional context in comments.

Comments

-3

Just use the del keyword:

delete arr["key"];

2 Comments

Do you mean the delete keyword? Anyway, that doesn't work on arrays, you'll just create an undefined entry. By the way, array keys are numeric, so "key" is not a valid one.
@phihag, it's not an undefined entry, it just doesn't alter .length, but it will delete the element. Try: t=[1];delete t[0];0 in t; is false.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.