js index of array code example

Example 1: get index of element in array js

const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];

console.log(beasts.indexOf('bison'));
// expected output: 1

// start from index 2
console.log(beasts.indexOf('bison', 2));
// expected output: 4

console.log(beasts.indexOf('giraffe'));
// expected output: -1

//*** Thanks to MDN Web Docs ***//
//https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Array/indexOf

Example 2: js array return only certain positions

const every_nth = (arr, nth) => arr.filter((e, i) => i % nth === nth - 1);
console.log(every_nth([1, 2, 3, 4, 5, 6], 1));
console.log(every_nth([1, 2, 3, 4, 5, 6], 2));
console.log(every_nth([1, 2, 3, 4, 5, 6], 3));
console.log(every_nth([1, 2, 3, 4, 5, 6], 4));

// OUTPUT

[1,2,3,4,5,6]
[2,4,6]
[3,6]
[4]

Example 3: js get index of item in array

array.indexOf("item");

Example 4: js array get index

var fruits = ["Banana", "Orange", "Apple", "Mango"];
return fruits.indexOf("Apple"); // Returns 2

Example 5: get index of element in array javascript

var scores = [10, 20, 30, 10, 40, 20];
console.log(scores.indexOf(30)); // 2
console.log(scores.indexOf(50)); // -1

Example 6: how to get the index of an array in javascript

search = (arr, item) => { return arr.indexOf(item); }