1

How can I know in which position "Januar" in the array is (in a number)?^ In the end, I want to get 0 for "January" and 1 for "February" .

var Monat = ["January", "February"]
DecPK
  • 24,537
  • 6
  • 26
  • 42
  • 2
    [Array.prototype.indexOf](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf) is your friend. – goto Apr 14 '21 at 12:05

3 Answers3

1

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

So in your case

 Monat.indexOf("January")

Should return 0

Risalat Zaman
  • 1,189
  • 1
  • 9
  • 19
0

You could use findIndex of Array.prototype to find the index.

var Monat = ["January", "February"];
function findIndex(day) {
  return Monat.findIndex((x) => x === day);
}

const index = findIndex("January");
console.log(index);
const index2 = findIndex("February");
console.log(index2);
DecPK
  • 24,537
  • 6
  • 26
  • 42
0

You can use indexOf for this. it will return the index of the first matched item in the array if found or -1 otherwise.

var Monat = ["January", "February"];

console.log(Monat.indexOf("January")); //0

console.log(Monat.indexOf("February")); //1

console.log(Monat.indexOf("not exists")); //-1
Ran Turner
  • 14,906
  • 5
  • 47
  • 53