indexOf() on array of objects returning why

I have an array that looks something like this:

var files = [
  {
    dir: '/home/runner/random-stuff',
    file: '03:39:36 @ Aug 24, 2020-turnover-log'
  },
  {
    dir: '/home/runner/random-stuff',
    file: '04:37:02 @ Sep 12, 2020-turnover-log'
  },
  {
    dir: '/home/runner/random-stuff',
    file: '04:52:08 @ Sep 12, 2020-turnover-log.txt'
  },
  {
    dir: '/home/runner/random-stuff',
    file: '21:23:23 @ Aug 21, 2020-turnover-log'
  },
  { dir: '/home/runner/random-stuff', file: 'current-log.txt' }
]

Evidently it’s an array of objects. I tried running this code:

files.indexOf({
    dir: '/home/runner/random-stuff',
    file: '03:39:36 @ Aug 24, 2020-turnover-log'
  })

>>> -1

Why does this happen?

Note: I’ve already solved the problem:

files.map(x => x.file).indexOf("current-log.txt")

For some reason,

files.findIndex(x => {
x.file == "current-log.txt"
})

doesn’t work. Why don’t these two methods work?

The above code doesn’t works because your anonymous func inside findIndex method is returning undefined, which is equivalent to false in JS.

Try the following,

files.findIndex(obj => obj.file == 'current-log.txt')
1 Like

This one will never work. It is because == operator compares two objects by their address/reference, not by their value.

2 Likes