E
E
Ella Fitzgerald2016-08-25 19:16:00
JavaScript
Ella Fitzgerald, 2016-08-25 19:16:00

How to implement the inArray function?

Good evening everyone! I'm still quite new to JS. What are prototypes and classes, I learned only yesterday. Please help me solve the problem, which is probably the simplest for you :)
It is required to implement a function, examples of which are presented below:

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

As I understand it, the inArray function checks for the presence of an element in the selected array and returns true if successful, otherwise false. I understand how to write it so that the first call from the example works. Like this for example:
function inArray(value, array) {
  for (var i = 0; i < array.length; i++) {
    if (value === array[i]) {
      return true;
    } 
  }
  return false;
}

inArray(15, [1, 10, 145, 8]); // false

But how do I need to rewrite it so that the second call option also works?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
D
DTX, 2016-08-25
@Elizaveta_Ozerova

function inArray(value, array) {
  if (!array)
    array = this;
  for (var i = 0; i < array.length; i++) {
    if (value === array[i]) {
      return true;
    } 
  }
  return false;
}
Array.prototype.inArray = inArray;
console.log([1, 10, 145, 8].inArray(10));
console.log(inArray(100, [1, 10, 145, 8]));

A
Alexey Ukolov, 2016-08-25
@alexey-m-ukolov

Array.prototype.inArray = function (item) {return this.indexOf(item) > -1}

Only, patching global objects is bad practice, you shouldn't do it outside of educational projects.
Well, your function should be rewritten to use indexOf(), there is no need to reinvent the wheel.

Y
yogurt1, 2016-08-25
@yogurt1

function inArray(key, arr) {
  return arr.map(i => i === key).length > 0
}

N
nikoyar, 2020-09-07
@nikoyar

For ES6

function inArray(key, arr) {
  return arr.some((id) => id == key)
}

You can also just arr.includes(key) , but here there is a strict comparison === inside and you can have problems with different data types

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question