[Vuejs]-Why am i getting 'i is not defined' error from a simple for loop in vue.js component script?

4👍

Try to add let i before using it in the for loop.
See example below.

for (let i in newArray) {
  if (i.version.startsWith('iPad')) {
    newlist.push(newlist.splice(i, 1)[0]);
  }
}

0👍

Several problems with the original code.

  1. The missing const/let on i
  2. in loop should be of. Or maybe not. The following lines seem to assume that i is both the index and the entry.
  3. newlist isn’t defined.
  4. It seems to be trying to mutate an array whilst iterating over it.

I think you’re looking for something more like this.

const newArray = sortBy(getData(), 'version').reverse()
const nonIPads = []
const iPads = []

for (const entry of newArray) {
  if (entry.version.startsWith('iPad')) {
    iPads.push(entry)
  } else {
    nonIPads.push(entry)
  }
}

const all = [...nonIPads, ...iPads]

console.log(all)

function sortBy(array, property) {
  return [...array].sort((a, b) => {
    const valueA = a[property]
    const valueB = b[property]

    if (valueA === valueB) {
      return 0
    }

    return valueA < valueB ? -1 : 1
  })
}

function getData() {
  return [
    {version: 'f'},
    {version: 'a'},
    {version: 'd'},
    {version: 'iPad 3'},
    {version: 'iPad 1'},
    {version: 'iPad 4'},
    {version: 'e'},
    {version: 'c'},
    {version: 'g'},
    {version: 'b'},
    {version: 'iPad 2'}
  ]
}

Leave a comment