Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save michaelmcshinsky/095aded968e0abf19d52f0adda3732b5 to your computer and use it in GitHub Desktop.
Save michaelmcshinsky/095aded968e0abf19d52f0adda3732b5 to your computer and use it in GitHub Desktop.
finding-objects-and-values-in-arrays-part-1
let namesArray = ['Adam', 'Bell', 'Cody', 'Dawn'];
let textArray = ['Dog', 'Cat', 'Horse', 'Cow'];
let numbersArray = [1, 2, 3, 4];
let arr = ['Adam', 'Bell', 'Cody', 'Adam', 'Dawn'];
let value = 'Adam';
// Array.indexOf()
let index1 = arr.indexOf(value); // 1 (first occurrence of value in the array)
console.log(arr[index1]); // 'Adam'
// Array.find()
let index2 = arr.find(x => x === value); // 1
console.log(arr[index2]); // 'Adam'
// Array.includes()
let exists = arr.includes(value); // true
let arr = ['Adam', 'Bell', 'Cody', 'Adam', 'Dawn'];
let value = 'Adam';
// Array.lastIndexOf()
let index1 = arr.lastIndexOf(value); // 3 (last occurrence of value in the array)
console.log(arr[index1]); // 'Adam'
// Array.findIndex()
let index2 = arr.findIndex(x => x === value); // 1
console.log(arr[index2]); // 'Adam'
// for loop
let arr = ['Adam', 'Bell', 'Cody', 'Adam', 'Dawn'];
let value = 'Adam';
let result = null;
for(let i = 0; i < arr.length; i++) {
if(i === val) {
result = i;
break; // We are looking for the first occurrence of value;
};
};
console.log(result); // 'Adam'
// while loop
let arr = ['Adam', 'Bell', 'Cody', 'Adam', 'Dawn'];
let value = 'Adam';
let result = null;
let j = 0;
while (j < arr.length) {
if (j === val) {
result = j;
break;
}
j = j + 1;
}
console.log(result); // 'Adam'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment