0

I have an Array of objects, example

Item[0] ="{ id1: 1}";
Item[1] ="{ id2: 2}"; 
Item[2] ="{ id3: 3}"; 

I have to delete an item by knowing an specific id. For example, if i get id2, i have to delete Item[1].

I tried to solve it, but it deletes the last item

for (var i = 0; i < items.length; i++) {
            var _item = items[i];
            var funcId = getValueKey(_item);

        if(funcId == _item)
        {
            delete items[i];
        }      
        };

The getValueKey func

getValueKey: function(obj){
        for (var key in obj) {
            if (obj.hasOwnProperty(key)) {
                return key;

            }
        }
8
  • 6
    This is an array of strings, not an array of objects. Commented Oct 29, 2013 at 13:21
  • 1
    What weird formatting is this? Why are you using strings? What makes your code "associative" when you don't refer to the ID in the array key? Commented Oct 29, 2013 at 13:21
  • You don't have array of objects. You have array of strings. Commented Oct 29, 2013 at 13:22
  • 2
    And if the strings weren't there, objects are key:val not key=val Commented Oct 29, 2013 at 13:22
  • 2
    @yoavmatchulsky There are shims anyway for ES5 features. Stop caring about old browsers ;) Commented Oct 29, 2013 at 13:25

2 Answers 2

1

I solved it, thanks to me..

for (var i = 0; i < items.length; i++) {
            var _item = items[i];
            var funcId = getValueKey(_item);
            if(funcId ==id) {
                delete items[i];
            }
Sign up to request clarification or add additional context in comments.

Comments

1

Your answer may work, but it seems like much more code than is required.

function removeMemberByValue(arr, value) {

  for (var i=0, iLen=arr.length; i<iLen; i++) {

    if (arr[i] && arr[i].hasOwnProperty(value));

      //Do 1 of the following, not both:

      // to remove member i (i.e. there will no longer be a member i)
      delete(arr[i]);

      // Remove member i and shift later members -1
      arr.splice(i, 1);

      return arr;  // return is optional
  }
}

In the above, the first option will result in removal of the member but all other members will keep the same index, e.g.

var arr = [{id1: 1}, {id2: 2}, {id3: 3}];
removeMemberByValue(arr, value); // [not defined, {id2: 2}, {id3: 3}]

where not defined means "does not exist".

The second option will move later members 1 lower in index, so:

removeMemberByValue(arr, value); // [{id2: 2}, {id3: 3}]

Choose whichever suits.

Comments

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.