-1

I am trying to sort an array by 'version' and then identify all string that begin with 'iPad'.

The following code does not log anything and returns an error.

orderedUsers: function () {
  let newarray = sortBy(this.jobs, 'version').reverse()
  for (let i in newarray) {
    if (i.version.startsWith('iPad')) {
      console.log(i.version);
    }
  }
  return newarray

error:

TypeError: Cannot read property 'startsWith' of undefined

If I remove the for-loop and just put:

orderedUsers: function () {
  let newarray = sortBy(this.jobs, 'version').reverse()
  return newarray

The list is correctly sorted by version. This makes me think the error is related to how I have written my for-loop or if statement.

What am I doing wrong here.

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
david
  • 6,303
  • 16
  • 54
  • 91
  • What is `this.jobs`? – Jack Bashford Jun 19 '19 at 21:18
  • `for..in` is used to iterate over an object. `i` in your loop is the index in the array. The index doesn't have a version property. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in#Array_iteration_and_for...in –  Jun 19 '19 at 21:18
  • I think I already covered this in my answer to your last question: https://stackoverflow.com/questions/56674240/why-am-i-getting-i-is-not-defined-error-from-a-simple-for-loop-in-vue-js-compo – skirtle Jun 19 '19 at 21:21
  • Possible duplicate of [why am i getting 'i is not defined' error from a simple for loop in vue.js component script?](https://stackoverflow.com/questions/56674240/why-am-i-getting-i-is-not-defined-error-from-a-simple-for-loop-in-vue-js-compo) –  Jun 19 '19 at 21:22
  • Relevant: https://stackoverflow.com/a/29397769/621962 – canon Jun 19 '19 at 21:27

2 Answers2

-1

The for...in construct is not doing what you think here. It is is designed to iterate over objects. So in this case it is treating newArray as an object but with the property names as the array indices. Arrays in Javascript are just objects with numeric property names. More specifically if you changed your code to:

for (let i in newarray) {
    if (i.version.startsWith('iPad')) {
      console.log(i);
    }
  }

You would clearly see the problem. i is a number and not a job object.

Choc13
  • 796
  • 7
  • 23
-1

fix:

orderedUsers: function () {
  let newarray = sortBy(this.jobs, 'version').reverse()
  for (let i in newarray) {
    if (newarray[i].version.startsWith('iPad')) {
      console.log(newarray[i].version);
    }
  }
  return newarray
david
  • 6,303
  • 16
  • 54
  • 91
  • 3
    You should really mark Jack's answer as correct, rather than posting his solution again. – Choc13 Jun 19 '19 at 21:25
  • 2
    I used amy's initial comment to fix - but will mark jacks as correct if that's the same thing – david Jun 19 '19 at 21:26