The examples below detail JavaScript and Apps Script methods for finding array elements: find() , findIndex () , indexOf() , lastIndexOf() , includes() , every() and some() .
Methods findIndex() , indexOf() and lastIndexOf() find the index of the array that satisfies the specified condition, and the find() method find its value.
The includes() method is convenient for use in the if operator, since it returns true if the item is found, and false if not.
The every() method checks that ALL elements of the array match the condition specified in the callback function, and the some() method checks Whether this condition satisfies at least ONE element of the array.
const arr = [1, 2, 3, 4, 5, 3];
// find() returns the VALUE of the FIRST item satisfies condition of the callback function
// OR return <underfined>
let valueGteater3 = arr.find(item => item > 3);
console.log(valueGteater3); // 4
let valueGteater5 = arr.find(item => item > 5);
console.log(valueGteater5); // undefined
// findIndex() returns the INDEX of the FIRST item satisfies condition of the callback function
// OR return <-1>
let indexItemGteater3 = arr.findIndex(item => item > 3);
console.log(valueGteater3); // 3
let indexItemGteater5 = arr.findIndex(item => item > 5);
console.log(valueGteater5); // -1
// variant for not first item
let notFirstItem = arr.find((item, index) => {
if (item > 3 && index > 3) return true;
});
console.log(notFirstItem); // 5
// indexOf() returns the INDEX of the FIRST item is equal the specified value
// OR return <-1>
let valueEqual3 = arr.indexOf(3);
console.log(valueEqual3); // 2
let valueEqual3Next = arr.indexOf(3, 3);
console.log(valueEqual3Next); // 5
let valueEqual1 = arr.indexOf(1, 3);
console.log(valueEqual1); // -1
// lastIndexOf() returns the INDEX of the LAST item is equal the specified value
// OR return <-1>
let valueEqual3Last = arr.lastIndexOf(3);
console.log(valueEqual3Last); // 5
let valueEqual3NextLast = arr.lastIndexOf(3, 4);
console.log(valueEqual3NextLast); // 2
let valueEqual5Last = arr.lastIndexOf(5, 3);
console.log(valueEqual5Last); // -1
// const arr = [1, 2, 3, 4, 5, 3];
// includes() returns TRUE is element is icluded in the array, and FALSE is not
let isIncludes3 = arr.includes(3);
console.log(isIncludes3); // true
let isIncludes6 = arr.includes(6);
console.log(isIncludes6); // false
// every() returns TRUE if ALL elements satisfy the condition, and FALSE is not
let allPositive = arr.every(item => item > 0);
console.log(allPositive); // true
let moreThen1 = arr.every(item => item > 1);
console.log(moreThen1); // false
// some() returns TRUE if AT LEAST ONE element satisfy the condition, and FALSE is not
let moreThen4 = arr.some(item => item > 4);
console.log(moreThen4); // true
let moreThen5 = arr.some(item => item > 5);
console.log(moreThen5); // false
You can find more information in this video (RU voice):