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

1
  • Maybe you mean array comparing, check this answer1, answer2 Commented Feb 14, 2016 at 18:46

3 Answers 3

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;}
Sign up to request clarification or add additional context in comments.

1 Comment

Bacause it can be modded to make it automatic from any other data and returning auto name of record or sth.
2

You can just use `includes' method

history.includes(5) // false
history.includes(0) // true

2 Comments

Arrays have no includes method (yet), just strings. history is an array.
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.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.