array position javascript code example

Example 1: 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 2: js get index of item in array

array.indexOf("item");

Example 3: js index of

const paragraph = 'The quick brown fox jumps over the lazy dog. If the dog barked, was it really lazy?';

const searchTerm = 'dog';
const indexOfFirst = paragraph.indexOf(searchTerm);

console.log(`The index of the first "${searchTerm}" from the beginning is ${indexOfFirst}`);
// expected output: "The index of the first "dog" from the beginning is 40"

console.log(`The index of the 2nd "${searchTerm}" is ${paragraph.indexOf(searchTerm, (indexOfFirst + 1))}`);
// expected output: "The index of the 2nd "dog" is 52"

Example 4: arrays

//Javascript Array
var fruitList = ["Bananas", "Apples", "Oranges"]

Example 5: check items in array javascript

function checkAllEven(arr) {
  return arr.every(function(x){
	 return	x % 2 === 0
	})
}

//using "every" to check every item in array.