0

How to realize JavaScript (without using any libraries) function inArray, call examples of which are given below?

inArray(15, [1, 10, 145, 8]) === false; [23, 674, 4, 12].inArray(4) === true;

Thank you very much!

Oksana
  • 11
  • 1
    [`indexOf`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf) or [`includes`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes) – Scott Aug 24 '16 at 17:55
  • This has been answered here : http://stackoverflow.com/questions/890782/javascript-function-inarray/890808#890808 – Kewin Dousse Aug 24 '16 at 17:56

4 Answers4

0

You're looking for indexOf

[23, 674, 4, 12].indexOf(4) >= 0 // evaluates to true
Jared Hooper
  • 881
  • 1
  • 10
  • 31
0
    function inArray(val, arr){
        return arr.indexOf(val) > -1;
    }
baskin
  • 139
  • 9
0

You can attach functions to the prototype of Array. That this may cause problems has been thoroughly discussed elsewhere.

function inArray(needle, haystack) {
  return haystack.indexOf(needle) >= 0;
}
Array.prototype.inArray = function(needle) {
  return inArray(needle, this);
}

console.log(inArray(15, [1, 10, 145, 8])); // false
console.log([23, 674, 4, 12].inArray(4));  // true
Community
  • 1
  • 1
TimoStaudinger
  • 41,396
  • 16
  • 88
  • 94
0

You can use indexOf with ES6 :

var inArray = (num, arr) => (arr.indexOf(num) === -1) ? false : true;
var myArray = [1 ,123, 45];
console.log(inArray(15, myArray)); // false
console.log(inArray(123, myArray));// true
kevin ternet
  • 4,514
  • 2
  • 19
  • 27