Bob Deckard
Bob Deckard

Reputation: 23

Finding indexOf value in javascript

I'm trying to write a function that returns the index of an object where the value is less than 100. It currently returns -1 indicating that none of the objects meet that criteria when in fact I know that one does. I imagine it's something simple that I am just spacing out on. Can anyone offer a suggestion? Thanks

var distance = [ 16996.054413094975,
  102.48330298955042,
  8930.89370465407,
  10856.832465874579,
  6820.160641562082,
  114.07012348350867,
  8730.587245583654,
  325.9682182750614,
  6247.132833741246,
  6528.189432909801,
  10856.170817339278,
  8036.961700844721,
  98.66650647724741,
  16265.209545673928,
  16266.769167269893,
  715.0404901364141,
  7121.899289338758 ];


var addresses = function(){
      for (var i = 0; i <= distance.length; i ++)
      var indexDistance = distance.indexOf((i) <= 100);
      console.log(indexDistance);
    };

addresses();

Upvotes: 1

Views: 90

Answers (2)

Carcigenicate
Carcigenicate

Reputation: 45826

indexOf returns the first index of the argument you give it. You're giving it an inequality, which evaluates to a boolean value before being passed. That means you're basically telling it to search for boolean values in an array that contains only numbers. That's why it's returning -1; your list doesn't contain any literal true or false values.

I believe you're looking for filter:

// Find all numbers <= 100
var smallest =
    filter(n => n <= 100, distance)

// Get their indices
var indices =
    map(n => distance.indexOf(n), smallest);

This will find all the indices of all the numbers. If you only want the index of the first number less than 100, you can simplify it a bit:

// Find all numbers less than 100
//  then grab the first
var smallest =
    filter(n => n <= 100, distance)[0]

// Get the index
var index =
    distance.indexOf(smallest). 

Upvotes: 0

user663031
user663031

Reputation:

This function already exists. It's called findIndex.

distance.findIndex(i => i <= 100)

Upvotes: 2

Related Questions