0

I am attempting to filter out duplicate objects before pushing each object to an array.

function collaborators() {
  var api = '/docs/' + doc_id + '/json';
  $.getJSON(api, {format: "json"} ).done(function(data) {
    var collaborators = [];
    for (var i = 0; i < data.notes.length; i++) {
      if ( data.notes[i].author === data.notes[i+1].author) {
        console.log('dup found')
        console.log(data.notes[i].author)
      } else {
        collaborators.push(data.notes[i].author);
      }
    }
  });
}

The console is showing "Uncaught TypeError: Cannot read property 'author' of undefined". However I am seeing the duplicate entry in console.log(data.notes[i].author), but the array is empty. What needs to be corrected?

Evan Emolo
  • 1,660
  • 4
  • 28
  • 44

1 Answers1

0

In the last iteration of your loop, there is no i+1:

data.notes[i+1]

Since this is undefined, calling .author on it will blow up. As the error indicates, data.notes[i+1] is undefined, therefore there is no property author of undefined.

James Montagne
  • 77,516
  • 14
  • 110
  • 130
  • Ah, ok. How is `console.log(data.notes[i].author)` still showing an entry though? – Evan Emolo May 02 '13 at 17:31
  • it executes just fine, right up until the final iteration of the loop. – James Montagne May 02 '13 at 17:32
  • @EvanEmolo The `console.log` call using just `i` will always execute just fine, because you have constrained the values of `i` to always be within the bounds of the array indices in your `for` loop declaration. However, when you get to the last value of `i` produced by the `for` loop, attempting to access `i+1` will try to access an array element that is one index farther than the array's maximum index. Some other languages would error there, but JavaScript is more lenient and will give back `undefined`. You then attempt to "dereference" `undefined` with `.author`, which causes the error. – ajp15243 May 02 '13 at 17:37