0

I've tried to delete multiple entries in an array.

These entries are objects and I need to locate the object meeting specific criteria.

    var pending = [];
    a.forEach(function(entry, index) {
        if(entry.b == data) {
            pending.push(index);
        }
    });
    pending.forEach(function(entry) {
        a.splice(entry, 1);
    });

The problem is that it only deletes half of what I want (when b = data) and even deletes some random entries...

Thank you for your help.

5
  • What's in a, what is data? What are you trying to keep, show us some relevant (albeit simplified) code, with variables filled in? Commented Oct 11, 2014 at 21:22
  • Its possible that you're getting false positives from your non-strict equality comparison. Have you stepped through this in the debugger? Commented Oct 11, 2014 at 21:23
  • 1
    With each splice(), the indexes in a shift for everything > entry, so the next entry is off by 1, next by 2, etc. Look into .filter(). Commented Oct 11, 2014 at 21:23
  • AHH~! that's right @JonathanLonowski! I've overlooked that fact! So .filter()?? Commented Oct 11, 2014 at 21:26
  • @cloud1250000 Yeah. David already posted an example of .filter(). It isn't a mutator like .splice(), so it won't alter a. It instead creates a new Array without the filtered element that you can assign back into a as a = a.filter(...);. Commented Oct 11, 2014 at 21:40

1 Answer 1

2

I'm assuming that a is an array of objects, that you want to filter in order to keep only those whose b property is equal to the string 'data'. That being the case:

// this outputs to the console, you should probably press 'F12'
var a = [{
    'b': 'data'
  }, {
    'b': 'something else'
  }, {
    'b': 'data'
  }, {
    'b': 50
  }],
  pending = a.filter(function(elem) {
    return elem.b === 'data';
  });

console.log(pending);

References:

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

2 Comments

So basically, I should redo an array where I keep the message I want?
Perfect! it's working great! I did that pending = a.filter(function(elem) { return elem.b != data; }); a = pending;

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.