1

Let's say I have an object of

var people = [
  {name: 'John'}, // 0
  {name: 'James'}, // 1
  {name: 'Sue'}, // 2
  {name: 'Mary'}, // 3
  {name: 'Will'}, // 4
  {name: 'Lukas'}, // 5
  {name: 'Sam'} // 6
];

and then I have this array: var history = [0, 2, 4, 6]; // we have John, Sue, Will and Sam

Using Lodash, or general JavaScript, how can I make it to return true or false if a entered value is found inside the history[] array.

For example, isInHistoryArray(5) would return false but isInHistoryArray(2) would return true

red
  • 305
  • 1
  • 4
  • 15
  • Maybe you mean array comparing, check this [answer1](http://stackoverflow.com/questions/7837456/how-to-compare-arrays-in-javascript), [answer2](http://stackoverflow.com/questions/20020551/how-to-compare-elements-in-an-array-javascript) – Anna Gabrielyan Feb 14 '16 at 18:46

3 Answers3

2

You can just use `includes' method

history.includes(5) // false
history.includes(0) // true
Mehdi Dehghani
  • 10,970
  • 6
  • 59
  • 64
  • Arrays have no `includes` method (yet), just strings. `history` is an array. – T.J. Crowder Feb 14 '16 at 18:49
  • `Array#includes` is a Stage 4 ES2016 proposal, which V8 implements. It's not broadly available yet, nor is the spec completed. It **should** be in the spec when it comes out, Stage 4 means "ready to include in the spec," but you need a cutting-edge JavaScript engine (or a polyfill) to use it. – T.J. Crowder Feb 14 '16 at 18:51
2

For example

You have list-array of players in the small game:

var people = [
  {name: 'John'},
  {name: 'James'},
  {name: 'Sue'},
  {name: 'Mary'},
  {name: 'Will'},
  {name: 'Lukas'},
  {name: 'Sam'}
];

And you have array of the... actually connected people:

var history = [0, 2, 4, 6];

Okay, lets say that both containers are in the global scope for comfort.

You can check it by this function body

function checkHistory(a){
for(var i = 0; i < history.length; i++){
   if(history[i] === a) return true;
}return false;}
Daniel Mizerski
  • 1,123
  • 1
  • 8
  • 24
1

Arrays have an indexOf method that compares what you give it against the entries in the array (using strict comparison, ===) and tells you the index of the first match, or -1 (specifically) if there is no match. So:

function isInHistoryArray(value) {
    return history.indexOf(value) !== -1;
}

In ES2015, there are also Array.find and Array.findIndex (both of which can be polyfilled on older engines) that let you supply a predicate callback, but you don't need that here as your entries are numbers and what you're checking is also a number.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875